• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.net.wifi.ScanResult.WIFI_BAND_60_GHZ;
24 import static android.net.wifi.ScanResult.WIFI_BAND_6_GHZ;
25 import static android.net.wifi.WifiAvailableChannel.FILTER_REGULATORY;
26 import static android.net.wifi.WifiAvailableChannel.OP_MODE_SAP;
27 import static android.net.wifi.WifiAvailableChannel.OP_MODE_STA;
28 import static android.net.wifi.WifiConfiguration.METERED_OVERRIDE_METERED;
29 import static android.net.wifi.WifiManager.ACTION_REMOVE_SUGGESTION_DISCONNECT;
30 import static android.net.wifi.WifiManager.CHANNEL_DATA_KEY_FREQUENCY_MHZ;
31 import static android.net.wifi.WifiManager.CHANNEL_DATA_KEY_NUM_AP;
32 import static android.net.wifi.WifiManager.COEX_RESTRICTION_SOFTAP;
33 import static android.net.wifi.WifiManager.COEX_RESTRICTION_WIFI_AWARE;
34 import static android.net.wifi.WifiManager.COEX_RESTRICTION_WIFI_DIRECT;
35 import static android.net.wifi.WifiManager.DEVICE_MOBILITY_STATE_STATIONARY;
36 import static android.net.wifi.WifiManager.EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1;
37 import static android.net.wifi.WifiManager.EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE;
38 import static android.net.wifi.WifiManager.IFACE_IP_MODE_CONFIGURATION_ERROR;
39 import static android.net.wifi.WifiManager.IFACE_IP_MODE_LOCAL_ONLY;
40 import static android.net.wifi.WifiManager.IFACE_IP_MODE_TETHERED;
41 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_GENERIC;
42 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE;
43 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_NO_CHANNEL;
44 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.ERROR_TETHERING_DISALLOWED;
45 import static android.net.wifi.WifiManager.LocalOnlyHotspotCallback.REQUEST_REGISTERED;
46 import static android.net.wifi.WifiManager.NOT_OVERRIDE_EXISTING_NETWORKS_ON_RESTORE;
47 import static android.net.wifi.WifiManager.SAP_START_FAILURE_GENERAL;
48 import static android.net.wifi.WifiManager.SAP_START_FAILURE_NO_CHANNEL;
49 import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLED;
50 import static android.net.wifi.WifiManager.WIFI_AP_STATE_DISABLING;
51 import static android.net.wifi.WifiManager.WIFI_AP_STATE_ENABLED;
52 import static android.net.wifi.WifiManager.WIFI_AP_STATE_FAILED;
53 import static android.net.wifi.WifiManager.WIFI_STATE_DISABLED;
54 import static android.net.wifi.WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_60_GHZ;
55 import static android.net.wifi.WifiScanner.WIFI_BAND_24_GHZ;
56 import static android.net.wifi.WifiScanner.WIFI_BAND_5_GHZ;
57 import static android.os.Process.WIFI_UID;
58 
59 import static com.android.dx.mockito.inline.extended.ExtendedMockito.mockitoSession;
60 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_LOCAL_ONLY;
61 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_PRIMARY;
62 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_SECONDARY_LONG_LIVED;
63 import static com.android.server.wifi.ActiveModeManager.ROLE_CLIENT_SECONDARY_TRANSIENT;
64 import static com.android.server.wifi.LocalOnlyHotspotRequestInfo.HOTSPOT_NO_ERROR;
65 import static com.android.server.wifi.SelfRecovery.REASON_API_CALL;
66 import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_NONE;
67 import static com.android.server.wifi.WifiSettingsConfigStore.SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI;
68 import static com.android.server.wifi.WifiSettingsConfigStore.SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API;
69 import static com.android.server.wifi.WifiSettingsConfigStore.WIFI_VERBOSE_LOGGING_ENABLED;
70 
71 import static com.google.common.truth.Truth.assertThat;
72 
73 import static org.junit.Assert.assertArrayEquals;
74 import static org.junit.Assert.assertEquals;
75 import static org.junit.Assert.assertFalse;
76 import static org.junit.Assert.assertNotNull;
77 import static org.junit.Assert.assertNull;
78 import static org.junit.Assert.assertThrows;
79 import static org.junit.Assert.assertTrue;
80 import static org.junit.Assert.fail;
81 import static org.junit.Assume.assumeTrue;
82 import static org.mockito.AdditionalAnswers.returnsSecondArg;
83 import static org.mockito.AdditionalMatchers.aryEq;
84 import static org.mockito.ArgumentMatchers.anyList;
85 import static org.mockito.ArgumentMatchers.anySet;
86 import static org.mockito.ArgumentMatchers.notNull;
87 import static org.mockito.ArgumentMatchers.nullable;
88 import static org.mockito.Matchers.any;
89 import static org.mockito.Matchers.anyString;
90 import static org.mockito.Matchers.eq;
91 import static org.mockito.Mockito.anyBoolean;
92 import static org.mockito.Mockito.anyInt;
93 import static org.mockito.Mockito.argThat;
94 import static org.mockito.Mockito.atLeastOnce;
95 import static org.mockito.Mockito.clearInvocations;
96 import static org.mockito.Mockito.doAnswer;
97 import static org.mockito.Mockito.doNothing;
98 import static org.mockito.Mockito.doReturn;
99 import static org.mockito.Mockito.doThrow;
100 import static org.mockito.Mockito.ignoreStubs;
101 import static org.mockito.Mockito.inOrder;
102 import static org.mockito.Mockito.isNull;
103 import static org.mockito.Mockito.lenient;
104 import static org.mockito.Mockito.mock;
105 import static org.mockito.Mockito.never;
106 import static org.mockito.Mockito.reset;
107 import static org.mockito.Mockito.spy;
108 import static org.mockito.Mockito.times;
109 import static org.mockito.Mockito.validateMockitoUsage;
110 import static org.mockito.Mockito.verify;
111 import static org.mockito.Mockito.verifyNoMoreInteractions;
112 import static org.mockito.Mockito.verifyZeroInteractions;
113 import static org.mockito.Mockito.when;
114 
115 import android.Manifest;
116 import android.app.ActivityManager;
117 import android.app.AppOpsManager;
118 import android.app.admin.DevicePolicyManager;
119 import android.app.admin.WifiSsidPolicy;
120 import android.app.compat.CompatChanges;
121 import android.app.test.MockAnswerUtil.AnswerWithArguments;
122 import android.bluetooth.BluetoothAdapter;
123 import android.compat.testing.PlatformCompatChangeRule;
124 import android.content.AttributionSource;
125 import android.content.BroadcastReceiver;
126 import android.content.ContentResolver;
127 import android.content.Context;
128 import android.content.Intent;
129 import android.content.IntentFilter;
130 import android.content.pm.ApplicationInfo;
131 import android.content.pm.PackageInfo;
132 import android.content.pm.PackageManager;
133 import android.content.res.Resources;
134 import android.hardware.wifi.WifiStatusCode;
135 import android.net.DhcpInfo;
136 import android.net.DhcpOption;
137 import android.net.DhcpResultsParcelable;
138 import android.net.MacAddress;
139 import android.net.Network;
140 import android.net.NetworkStack;
141 import android.net.Uri;
142 import android.net.wifi.CoexUnsafeChannel;
143 import android.net.wifi.IActionListener;
144 import android.net.wifi.IBooleanListener;
145 import android.net.wifi.ICoexCallback;
146 import android.net.wifi.IDppCallback;
147 import android.net.wifi.IIntegerListener;
148 import android.net.wifi.IInterfaceCreationInfoCallback;
149 import android.net.wifi.ILastCallerListener;
150 import android.net.wifi.IListListener;
151 import android.net.wifi.ILocalOnlyConnectionStatusListener;
152 import android.net.wifi.ILocalOnlyHotspotCallback;
153 import android.net.wifi.INetworkRequestMatchCallback;
154 import android.net.wifi.IOnWifiActivityEnergyInfoListener;
155 import android.net.wifi.IOnWifiDriverCountryCodeChangedListener;
156 import android.net.wifi.IOnWifiUsabilityStatsListener;
157 import android.net.wifi.IPnoScanResultsCallback;
158 import android.net.wifi.IScanResultsCallback;
159 import android.net.wifi.ISoftApCallback;
160 import android.net.wifi.IStringListener;
161 import android.net.wifi.ISubsystemRestartCallback;
162 import android.net.wifi.ISuggestionConnectionStatusListener;
163 import android.net.wifi.ISuggestionUserApprovalStatusListener;
164 import android.net.wifi.ITrafficStateCallback;
165 import android.net.wifi.IWifiBandsListener;
166 import android.net.wifi.IWifiConnectedNetworkScorer;
167 import android.net.wifi.IWifiLowLatencyLockListener;
168 import android.net.wifi.IWifiNetworkSelectionConfigListener;
169 import android.net.wifi.IWifiNetworkStateChangedListener;
170 import android.net.wifi.IWifiVerboseLoggingStatusChangedListener;
171 import android.net.wifi.QosPolicyParams;
172 import android.net.wifi.ScanResult;
173 import android.net.wifi.SecurityParams;
174 import android.net.wifi.SoftApCapability;
175 import android.net.wifi.SoftApConfiguration;
176 import android.net.wifi.SoftApInfo;
177 import android.net.wifi.WifiAvailableChannel;
178 import android.net.wifi.WifiBands;
179 import android.net.wifi.WifiClient;
180 import android.net.wifi.WifiConfiguration;
181 import android.net.wifi.WifiConfiguration.KeyMgmt;
182 import android.net.wifi.WifiContext;
183 import android.net.wifi.WifiEnterpriseConfig;
184 import android.net.wifi.WifiInfo;
185 import android.net.wifi.WifiManager;
186 import android.net.wifi.WifiManager.LocalOnlyHotspotCallback;
187 import android.net.wifi.WifiNetworkSelectionConfig;
188 import android.net.wifi.WifiNetworkSuggestion;
189 import android.net.wifi.WifiScanner;
190 import android.net.wifi.WifiSsid;
191 import android.net.wifi.hotspot2.IProvisioningCallback;
192 import android.net.wifi.hotspot2.OsuProvider;
193 import android.net.wifi.hotspot2.PasspointConfiguration;
194 import android.net.wifi.hotspot2.pps.Credential;
195 import android.net.wifi.hotspot2.pps.HomeSp;
196 import android.os.Binder;
197 import android.os.Build;
198 import android.os.Bundle;
199 import android.os.Handler;
200 import android.os.HandlerThread;
201 import android.os.IBinder;
202 import android.os.IPowerManager;
203 import android.os.IThermalService;
204 import android.os.Parcel;
205 import android.os.ParcelFileDescriptor;
206 import android.os.PowerManager;
207 import android.os.Process;
208 import android.os.RemoteException;
209 import android.os.UserHandle;
210 import android.os.UserManager;
211 import android.os.WorkSource;
212 import android.os.connectivity.WifiActivityEnergyInfo;
213 import android.os.test.TestLooper;
214 import android.telephony.CarrierConfigManager;
215 import android.telephony.PhoneStateListener;
216 import android.telephony.SubscriptionManager;
217 import android.telephony.TelephonyManager;
218 import android.util.Pair;
219 
220 import androidx.test.filters.SmallTest;
221 
222 import com.android.internal.os.PowerProfile;
223 import com.android.modules.utils.ParceledListSlice;
224 import com.android.modules.utils.build.SdkLevel;
225 import com.android.server.wifi.WifiServiceImpl.LocalOnlyRequestorCallback;
226 import com.android.server.wifi.WifiServiceImpl.SoftApCallbackInternal;
227 import com.android.server.wifi.coex.CoexManager;
228 import com.android.server.wifi.entitlement.PseudonymInfo;
229 import com.android.server.wifi.hotspot2.PasspointManager;
230 import com.android.server.wifi.hotspot2.PasspointProvisioningTestUtil;
231 import com.android.server.wifi.proto.WifiStatsLog;
232 import com.android.server.wifi.proto.nano.WifiMetricsProto.UserActionEvent;
233 import com.android.server.wifi.util.ActionListenerWrapper;
234 import com.android.server.wifi.util.ApConfigUtil;
235 import com.android.server.wifi.util.LastCallerInfoManager;
236 import com.android.server.wifi.util.WifiPermissionsUtil;
237 import com.android.server.wifi.util.WifiPermissionsWrapper;
238 import com.android.wifi.resources.R;
239 
240 import com.google.common.base.Strings;
241 
242 import org.junit.After;
243 import org.junit.Before;
244 import org.junit.Rule;
245 import org.junit.Test;
246 import org.junit.rules.TestRule;
247 import org.mockito.ArgumentCaptor;
248 import org.mockito.ArgumentMatcher;
249 import org.mockito.Captor;
250 import org.mockito.InOrder;
251 import org.mockito.Mock;
252 import org.mockito.MockitoAnnotations;
253 import org.mockito.MockitoSession;
254 
255 import java.io.FileDescriptor;
256 import java.io.PrintWriter;
257 import java.io.StringWriter;
258 import java.util.ArrayList;
259 import java.util.Arrays;
260 import java.util.Collections;
261 import java.util.HashMap;
262 import java.util.List;
263 import java.util.Map;
264 import java.util.Optional;
265 import java.util.Set;
266 
267 /**
268  * Unit tests for {@link WifiServiceImpl}.
269  *
270  * Note: this is intended to build up over time and will not immediately cover the entire file.
271  */
272 @SmallTest
273 public class WifiServiceImplTest extends WifiBaseTest {
274 
275     private static final String TAG = "WifiServiceImplTest";
276     private static final String SCAN_PACKAGE_NAME = "scanPackage";
277     private static final int DEFAULT_VERBOSE_LOGGING = 0;
278     private static final String ANDROID_SYSTEM_PACKAGE = "android";
279     private static final String TEST_PACKAGE_NAME = "TestPackage";
280     private static final String TEST_PACKAGE_NAME_OTHER = "TestPackageOther";
281     private static final String TEST_FEATURE_ID = "TestFeature";
282     private static final String SYSUI_PACKAGE_NAME = "com.android.systemui";
283     private static final int TEST_PID = 6789;
284     private static final int TEST_PID2 = 9876;
285     private static final int TEST_UID = 1200000;
286     private static final int OTHER_TEST_UID = 1300000;
287     private static final int TEST_USER_HANDLE = 13;
288     private static final int TEST_WIFI_CONNECTED_NETWORK_SCORER_IDENTIFIER = 1;
289     private static final String WIFI_IFACE_NAME = "wlan0";
290     private static final String WIFI_IFACE_NAME2 = "wlan1";
291     private static final String TEST_COUNTRY_CODE = "US";
292     private static final String TEST_NEW_COUNTRY_CODE = "TW";
293     private static final String TEST_FACTORY_MAC = "10:22:34:56:78:92";
294     private static final MacAddress TEST_FACTORY_MAC_ADDR = MacAddress.fromString(TEST_FACTORY_MAC);
295     private static final String TEST_FQDN = "testfqdn";
296     private static final String TEST_FRIENDLY_NAME = "testfriendlyname";
297     private static final List<WifiConfiguration> TEST_WIFI_CONFIGURATION_LIST = Arrays.asList(
298             WifiConfigurationTestUtil.generateWifiConfig(
299                     0, 1000000, "\"red\"", true, true, null, null,
300                     SECURITY_NONE),
301             WifiConfigurationTestUtil.generateWifiConfig(
302                     1, 1000001, "\"green\"", true, false, "example.com", "Green",
303                     SECURITY_NONE),
304             WifiConfigurationTestUtil.generateWifiConfig(
305                     2, 1200000, "\"blue\"", false, true, null, null,
306                     SECURITY_NONE),
307             WifiConfigurationTestUtil.generateWifiConfig(
308                     3, 1100000, "\"cyan\"", true, true, null, null,
309                     SECURITY_NONE),
310             WifiConfigurationTestUtil.generateWifiConfig(
311                     4, 1100001, "\"yellow\"", true, true, "example.org", "Yellow",
312                     SECURITY_NONE),
313             WifiConfigurationTestUtil.generateWifiConfig(
314                     5, 1100002, "\"magenta\"", false, false, null, null,
315                     SECURITY_NONE));
316     private static final int TEST_AP_FREQUENCY = 2412;
317     private static final int TEST_AP_BANDWIDTH = SoftApInfo.CHANNEL_WIDTH_20MHZ;
318     private static final int NETWORK_CALLBACK_ID = 1100;
319     private static final String TEST_CAP = "[RSN-PSK-CCMP]";
320     private static final String TEST_SSID = "Sid's Place";
321     private static final String TEST_SSID_WITH_QUOTES = "\"" + TEST_SSID + "\"";
322     private static final String TEST_BSSID = "01:02:03:04:05:06";
323     private static final String TEST_IP = "192.168.49.5";
324     private static final String TEST_PACKAGE = "package";
325     private static final int TEST_NETWORK_ID = 567;
326     private static final WorkSource TEST_SETTINGS_WORKSOURCE = new WorkSource();
327     private static final int TEST_SUB_ID = 1;
328     private static final byte[] TEST_OUI = new byte[]{0x01, 0x02, 0x03};
329     private static final int TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS = 1000;
330 
331     private SoftApInfo mTestSoftApInfo;
332     private List<SoftApInfo> mTestSoftApInfoList;
333     private Map<String, List<WifiClient>> mTestSoftApClients;
334     private Map<String, SoftApInfo> mTestSoftApInfos;
335     private WifiServiceImpl mWifiServiceImpl;
336     private TestLooper mLooper;
337     private WifiThreadRunner mWifiThreadRunner;
338     private PowerManager mPowerManager;
339     private PhoneStateListener mPhoneStateListener;
340     private int mPid;
341     private int mPid2 = Process.myPid();
342     private OsuProvider mOsuProvider;
343     private SoftApCallbackInternal mStateMachineSoftApCallback;
344     private SoftApCallbackInternal mLohsApCallback;
345     private String mLohsInterfaceName;
346     private ApplicationInfo mApplicationInfo;
347     private List<ClientModeManager> mClientModeManagers;
348     private Bundle mExtras = new Bundle();
349     private Bundle mAttribution = new Bundle();
350     private static final String DPP_URI = "DPP:some_dpp_uri";
351     private static final String DPP_PRODUCT_INFO = "DPP:some_dpp_uri_info";
352     private static final WorkSource SETTINGS_WORKSOURCE =
353             new WorkSource(Process.SYSTEM_UID, "system-service");
354 
355     private final ArgumentCaptor<BroadcastReceiver> mBroadcastReceiverCaptor =
356             ArgumentCaptor.forClass(BroadcastReceiver.class);
357 
358     final ArgumentCaptor<SoftApModeConfiguration> mSoftApModeConfigCaptor =
359             ArgumentCaptor.forClass(SoftApModeConfiguration.class);
360 
361     @Mock Bundle mBundle;
362     @Mock WifiContext mContext;
363     @Mock Context mContextAsUser;
364     @Mock WifiInjector mWifiInjector;
365     @Mock WifiCountryCode mWifiCountryCode;
366     @Mock Clock mClock;
367     @Mock WifiTrafficPoller mWifiTrafficPoller;
368     @Mock ConcreteClientModeManager mClientModeManager;
369     @Mock ActiveModeWarden mActiveModeWarden;
370     @Mock HandlerThread mHandlerThread;
371     @Mock Resources mResources;
372     @Mock FrameworkFacade mFrameworkFacade;
373     @Mock WifiLockManager mLockManager;
374     @Mock WifiMulticastLockManager mWifiMulticastLockManager;
375     @Mock WifiLastResortWatchdog mWifiLastResortWatchdog;
376     @Mock WifiBackupRestore mWifiBackupRestore;
377     @Mock SoftApBackupRestore mSoftApBackupRestore;
378     @Mock WifiMetrics mWifiMetrics;
379     @Mock WifiPermissionsUtil mWifiPermissionsUtil;
380     @Mock WifiPermissionsWrapper mWifiPermissionsWrapper;
381     @Mock WifiSettingsStore mSettingsStore;
382     @Mock ContentResolver mContentResolver;
383     @Mock PackageManager mPackageManager;
384     @Mock UserManager mUserManager;
385     @Mock WifiApConfigStore mWifiApConfigStore;
386     @Mock WifiConfiguration mApConfig;
387     @Mock ActivityManager mActivityManager;
388     @Mock AppOpsManager mAppOpsManager;
389     @Mock IBinder mAppBinder;
390     @Mock IBinder mAnotherAppBinder;
391     @Mock LocalOnlyHotspotRequestInfo mRequestInfo;
392     @Mock LocalOnlyHotspotRequestInfo mRequestInfo2;
393     @Mock IProvisioningCallback mProvisioningCallback;
394     @Mock ISoftApCallback mClientSoftApCallback;
395     @Mock ISoftApCallback mAnotherSoftApCallback;
396     @Mock PowerProfile mPowerProfile;
397     @Mock WifiTrafficPoller mWifiTrafficPolller;
398     @Mock ScanRequestProxy mScanRequestProxy;
399     @Mock WakeupController mWakeupController;
400     @Mock ITrafficStateCallback mTrafficStateCallback;
401     @Mock INetworkRequestMatchCallback mNetworkRequestMatchCallback;
402     @Mock WifiNetworkSuggestionsManager mWifiNetworkSuggestionsManager;
403     @Mock TelephonyManager mTelephonyManager;
404     @Mock CoexManager mCoexManager;
405     @Mock IOnWifiUsabilityStatsListener mOnWifiUsabilityStatsListener;
406     @Mock WifiConfigManager mWifiConfigManager;
407     @Mock WifiBlocklistMonitor mWifiBlocklistMonitor;
408     @Mock WifiScoreCard mWifiScoreCard;
409     @Mock WifiHealthMonitor mWifiHealthMonitor;
410     @Mock PasspointManager mPasspointManager;
411     @Mock DeviceConfigFacade mDeviceConfigFacade;
412     @Mock IDppCallback mDppCallback;
413     @Mock ILocalOnlyHotspotCallback mLohsCallback;
414     @Mock ICoexCallback mCoexCallback;
415     @Mock IScanResultsCallback mScanResultsCallback;
416     @Mock ISuggestionConnectionStatusListener mSuggestionConnectionStatusListener;
417     @Mock ILocalOnlyConnectionStatusListener mLocalOnlyConnectionStatusListener;
418     @Mock ISuggestionUserApprovalStatusListener mSuggestionUserApprovalStatusListener;
419     @Mock IOnWifiActivityEnergyInfoListener mOnWifiActivityEnergyInfoListener;
420     @Mock ISubsystemRestartCallback mSubsystemRestartCallback;
421     @Mock IWifiConnectedNetworkScorer mWifiConnectedNetworkScorer;
422     @Mock WifiSettingsConfigStore mWifiSettingsConfigStore;
423     @Mock WifiScanAlwaysAvailableSettingsCompatibility mScanAlwaysAvailableSettingsCompatibility;
424     @Mock PackageInfo mPackageInfo;
425     @Mock WifiConnectivityManager mWifiConnectivityManager;
426     @Mock WifiDataStall mWifiDataStall;
427     @Mock WifiNative mWifiNative;
428     @Mock ConnectHelper mConnectHelper;
429     @Mock IActionListener mActionListener;
430     @Mock WifiNetworkFactory mWifiNetworkFactory;
431     @Mock UntrustedWifiNetworkFactory mUntrustedWifiNetworkFactory;
432     @Mock OemWifiNetworkFactory mOemWifiNetworkFactory;
433     @Mock RestrictedWifiNetworkFactory mRestrictedWifiNetworkFactory;
434     @Mock MultiInternetManager mMultiInternetManager;
435     @Mock MultiInternetWifiNetworkFactory mMultiInternetWifiNetworkFactory;
436     @Mock WifiDiagnostics mWifiDiagnostics;
437     @Mock WifiP2pConnection mWifiP2pConnection;
438     @Mock SimRequiredNotifier mSimRequiredNotifier;
439     @Mock WifiGlobals mWifiGlobals;
440     @Mock AdaptiveConnectivityEnabledSettingObserver mAdaptiveConnectivityEnabledSettingObserver;
441     @Mock MakeBeforeBreakManager mMakeBeforeBreakManager;
442     @Mock WifiCarrierInfoManager mWifiCarrierInfoManager;
443     @Mock WifiPseudonymManager mWifiPseudonymManager;
444     @Mock OpenNetworkNotifier mOpenNetworkNotifier;
445     @Mock WifiNotificationManager mWifiNotificationManager;
446     @Mock SarManager mSarManager;
447     @Mock SelfRecovery mSelfRecovery;
448     @Mock LastCallerInfoManager mLastCallerInfoManager;
449     @Mock BuildProperties mBuildProperties;
450     @Mock LinkProbeManager mLinkProbeManager;
451     @Mock IOnWifiDriverCountryCodeChangedListener mIOnWifiDriverCountryCodeChangedListener;
452     @Mock WifiShellCommand mWifiShellCommand;
453     @Mock DevicePolicyManager mDevicePolicyManager;
454     @Mock HalDeviceManager mHalDeviceManager;
455     @Mock WifiDialogManager mWifiDialogManager;
456     @Mock SsidTranslator mSsidTranslator;
457     @Mock InterfaceConflictManager mInterfaceConflictManager;
458     @Mock WifiKeyStore mWifiKeyStore;
459     @Mock WifiPulledAtomLogger mWifiPulledAtomLogger;
460     @Mock ScoringParams mScoringParams;
461     @Mock ApplicationQosPolicyRequestHandler mApplicationQosPolicyRequestHandler;
462 
463     @Captor ArgumentCaptor<Intent> mIntentCaptor;
464     @Captor ArgumentCaptor<List> mListCaptor;
465 
466     @Rule
467     // For frameworks
468     public TestRule compatChangeRule = new PlatformCompatChangeRule();
469 
470     private MockitoSession mSession;
471 
472     WifiConfiguration mWifiConfig;
473 
474     WifiLog mLog;
475 
setUp()476     @Before public void setUp() throws Exception {
477         MockitoAnnotations.initMocks(this);
478         mSession = mockitoSession()
479                 .mockStatic(SubscriptionManager.class)
480                 .mockStatic(CompatChanges.class)
481                 .startMocking();
482 
483         mLog = spy(new LogcatLog(TAG));
484         mLooper = new TestLooper();
485         mApplicationInfo = new ApplicationInfo();
486         mApplicationInfo.targetSdkVersion = Build.VERSION_CODES.CUR_DEVELOPMENT;
487         when(mResources.getInteger(
488                 eq(R.integer.config_wifiHardwareSoftapMaxClientCount)))
489                 .thenReturn(10);
490         WifiInjector.sWifiInjector = mWifiInjector;
491         when(mRequestInfo.getPid()).thenReturn(mPid);
492         when(mRequestInfo2.getPid()).thenReturn(mPid2);
493         when(mWifiInjector.getUserManager()).thenReturn(mUserManager);
494         when(mWifiInjector.getWifiCountryCode()).thenReturn(mWifiCountryCode);
495         when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics);
496         when(mWifiInjector.getWifiNetworkFactory()).thenReturn(mWifiNetworkFactory);
497         when(mWifiInjector.getUntrustedWifiNetworkFactory())
498                 .thenReturn(mUntrustedWifiNetworkFactory);
499         when(mWifiInjector.getOemWifiNetworkFactory()).thenReturn(mOemWifiNetworkFactory);
500         when(mWifiInjector.getRestrictedWifiNetworkFactory())
501                 .thenReturn(mRestrictedWifiNetworkFactory);
502         when(mWifiInjector.getMultiInternetWifiNetworkFactory())
503                 .thenReturn(mMultiInternetWifiNetworkFactory);
504         when(mWifiInjector.getMultiInternetManager()).thenReturn(mMultiInternetManager);
505         when(mWifiInjector.getWifiDiagnostics()).thenReturn(mWifiDiagnostics);
506         when(mWifiInjector.getActiveModeWarden()).thenReturn(mActiveModeWarden);
507         when(mWifiInjector.getWifiHandlerThread()).thenReturn(mHandlerThread);
508         when(mWifiInjector.getMakeBeforeBreakManager()).thenReturn(mMakeBeforeBreakManager);
509         when(mWifiInjector.getWifiNotificationManager()).thenReturn(mWifiNotificationManager);
510         when(mWifiInjector.getBuildProperties()).thenReturn(mBuildProperties);
511         when(mWifiInjector.getLinkProbeManager()).thenReturn(mLinkProbeManager);
512         when(mWifiInjector.makeWifiShellCommand(any())).thenReturn(mWifiShellCommand);
513         // needed to mock this to call "handleBootCompleted"
514         when(mWifiInjector.getPasspointProvisionerHandlerThread())
515                 .thenReturn(mock(HandlerThread.class));
516         when(mHandlerThread.getThreadHandler()).thenReturn(new Handler(mLooper.getLooper()));
517         when(mHandlerThread.getLooper()).thenReturn(mLooper.getLooper());
518         when(mContext.getResources()).thenReturn(mResources);
519         when(mContext.getContentResolver()).thenReturn(mContentResolver);
520         when(mContext.getPackageManager()).thenReturn(mPackageManager);
521         when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(mPackageInfo);
522         when(mPackageManager.checkSignatures(anyInt(), anyInt()))
523                 .thenReturn(PackageManager.SIGNATURE_NO_MATCH);
524         when(mWifiInjector.getWifiApConfigStore()).thenReturn(mWifiApConfigStore);
525         doNothing().when(mFrameworkFacade).registerContentObserver(eq(mContext), any(),
526                 anyBoolean(), any());
527         when(mFrameworkFacade.getSettingsWorkSource(any())).thenReturn(TEST_SETTINGS_WORKSOURCE);
528         when(mContext.getSystemService(ActivityManager.class)).thenReturn(mActivityManager);
529         when(mContext.getSystemService(Context.APP_OPS_SERVICE)).thenReturn(mAppOpsManager);
530         IPowerManager powerManagerService = mock(IPowerManager.class);
531         IThermalService thermalService = mock(IThermalService.class);
532         mPowerManager =
533                 new PowerManager(mContext, powerManagerService, thermalService, new Handler());
534         when(mContext.getSystemServiceName(PowerManager.class)).thenReturn(Context.POWER_SERVICE);
535         when(mContext.getSystemService(PowerManager.class)).thenReturn(mPowerManager);
536         when(mContext.createContextAsUser(eq(UserHandle.CURRENT), anyInt()))
537                 .thenReturn(mContextAsUser);
538         when(mWifiInjector.getFrameworkFacade()).thenReturn(mFrameworkFacade);
539         when(mWifiInjector.getWifiLockManager()).thenReturn(mLockManager);
540         when(mWifiInjector.getWifiMulticastLockManager()).thenReturn(mWifiMulticastLockManager);
541         when(mWifiInjector.getWifiLastResortWatchdog()).thenReturn(mWifiLastResortWatchdog);
542         when(mWifiInjector.getWifiBackupRestore()).thenReturn(mWifiBackupRestore);
543         when(mWifiInjector.getSoftApBackupRestore()).thenReturn(mSoftApBackupRestore);
544         when(mWifiInjector.makeLog(anyString())).thenReturn(mLog);
545         when(mWifiInjector.getWifiTrafficPoller()).thenReturn(mWifiTrafficPoller);
546         when(mWifiInjector.getWifiPermissionsUtil()).thenReturn(mWifiPermissionsUtil);
547         when(mWifiInjector.getWifiPermissionsWrapper()).thenReturn(mWifiPermissionsWrapper);
548         when(mWifiInjector.getWifiSettingsStore()).thenReturn(mSettingsStore);
549         when(mWifiInjector.getClock()).thenReturn(mClock);
550         when(mWifiInjector.getScanRequestProxy()).thenReturn(mScanRequestProxy);
551         when(mWifiInjector.getWakeupController()).thenReturn(mWakeupController);
552         when(mWifiInjector.getWifiNetworkSuggestionsManager())
553                 .thenReturn(mWifiNetworkSuggestionsManager);
554         when(mWifiInjector.makeTelephonyManager()).thenReturn(mTelephonyManager);
555         when(mWifiInjector.getWifiPulledAtomLogger()).thenReturn(mWifiPulledAtomLogger);
556         when(mContext.getSystemService(TelephonyManager.class)).thenReturn(mTelephonyManager);
557         when(mWifiInjector.getCoexManager()).thenReturn(mCoexManager);
558         when(mWifiInjector.getWifiConfigManager()).thenReturn(mWifiConfigManager);
559         when(mWifiInjector.getWifiBlocklistMonitor()).thenReturn(mWifiBlocklistMonitor);
560         when(mWifiInjector.getPasspointManager()).thenReturn(mPasspointManager);
561         when(mWifiInjector.getDeviceConfigFacade()).thenReturn(mDeviceConfigFacade);
562         when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(mClientModeManager);
563         when(mClientModeManager.getInterfaceName()).thenReturn(WIFI_IFACE_NAME);
564         when(mWifiInjector.getWifiScoreCard()).thenReturn(mWifiScoreCard);
565         when(mWifiInjector.getWifiHealthMonitor()).thenReturn(mWifiHealthMonitor);
566 
567         mWifiThreadRunner = new WifiThreadRunner(new Handler(mLooper.getLooper()));
568         mWifiThreadRunner.setTimeoutsAreErrors(true);
569         when(mWifiInjector.getWifiThreadRunner()).thenReturn(mWifiThreadRunner);
570 
571         when(mWifiInjector.getSettingsConfigStore()).thenReturn(mWifiSettingsConfigStore);
572         when(mWifiInjector.getWifiScanAlwaysAvailableSettingsCompatibility())
573                 .thenReturn(mScanAlwaysAvailableSettingsCompatibility);
574         when(mWifiInjector.getWifiConnectivityManager()).thenReturn(mWifiConnectivityManager);
575         when(mWifiInjector.getWifiDataStall()).thenReturn(mWifiDataStall);
576         when(mWifiInjector.getWifiNative()).thenReturn(mWifiNative);
577         when(mWifiInjector.getConnectHelper()).thenReturn(mConnectHelper);
578         when(mWifiInjector.getWifiP2pConnection()).thenReturn(mWifiP2pConnection);
579         when(mWifiInjector.getSimRequiredNotifier()).thenReturn(mSimRequiredNotifier);
580         when(mWifiInjector.getWifiGlobals()).thenReturn(mWifiGlobals);
581         when(mWifiInjector.getAdaptiveConnectivityEnabledSettingObserver())
582                 .thenReturn(mAdaptiveConnectivityEnabledSettingObserver);
583         when(mClientModeManager.syncStartSubscriptionProvisioning(anyInt(),
584                 any(OsuProvider.class), any(IProvisioningCallback.class))).thenReturn(true);
585         // Create an OSU provider that can be provisioned via an open OSU AP
586         mOsuProvider = PasspointProvisioningTestUtil.generateOsuProvider(true);
587         when(mContext.getOpPackageName()).thenReturn(TEST_PACKAGE_NAME);
588         when(mContext.getAttributionTag()).thenReturn(TEST_FEATURE_ID);
589         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
590                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
591         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
592                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
593         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_STACK),
594                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
595         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_MANAGED_PROVISIONING),
596                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
597         when(mScanRequestProxy.startScan(anyInt(), anyString())).thenReturn(true);
598         when(mLohsCallback.asBinder()).thenReturn(mock(IBinder.class));
599         when(mWifiSettingsConfigStore.get(eq(WIFI_VERBOSE_LOGGING_ENABLED))).thenReturn(true);
600         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(false);
601         when(mActiveModeWarden.getClientModeManagersInRoles(
602                 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED))
603                 .thenReturn(Collections.emptyList());
604         when(mWifiPermissionsUtil.doesUidBelongToCurrentUserOrDeviceOwner(anyInt()))
605                 .thenReturn(true);
606         // Defaulting apps to target SDK level that's prior to T. This is needed to test for
607         // backward compatibility of API changes.
608         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
609                 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(true);
610         when(mWifiPermissionsUtil.isTargetSdkLessThan(any(),
611                 eq(Build.VERSION_CODES.UPSIDE_DOWN_CAKE),
612                 anyInt())).thenReturn(true);
613         when(mWifiInjector.getWifiCarrierInfoManager()).thenReturn(mWifiCarrierInfoManager);
614         when(mWifiInjector.getWifiPseudonymManager()).thenReturn(mWifiPseudonymManager);
615         when(mWifiInjector.getOpenNetworkNotifier()).thenReturn(mOpenNetworkNotifier);
616         when(mClientSoftApCallback.asBinder()).thenReturn(mAppBinder);
617         when(mAnotherSoftApCallback.asBinder()).thenReturn(mAnotherAppBinder);
618         when(mIOnWifiDriverCountryCodeChangedListener.asBinder()).thenReturn(mAppBinder);
619         when(mWifiInjector.getSarManager()).thenReturn(mSarManager);
620         mClientModeManagers = Arrays.asList(mClientModeManager, mock(ClientModeManager.class));
621         when(mActiveModeWarden.getClientModeManagers()).thenReturn(mClientModeManagers);
622         when(mWifiInjector.getSelfRecovery()).thenReturn(mSelfRecovery);
623         when(mWifiInjector.getLastCallerInfoManager()).thenReturn(mLastCallerInfoManager);
624         when(mUserManager.getUserRestrictions()).thenReturn(mBundle);
625         when(mContext.getSystemService(DevicePolicyManager.class)).thenReturn(mDevicePolicyManager);
626         when(mWifiInjector.getHalDeviceManager()).thenReturn(mHalDeviceManager);
627         when(mWifiInjector.getWifiDialogManager()).thenReturn(mWifiDialogManager);
628         when(mWifiInjector.getSsidTranslator()).thenReturn(mSsidTranslator);
629         when(mWifiInjector.getInterfaceConflictManager()).thenReturn(mInterfaceConflictManager);
630         when(mWifiInjector.getWifiKeyStore()).thenReturn(mWifiKeyStore);
631         when(mWifiInjector.getScoringParams()).thenReturn(mScoringParams);
632         when(mWifiInjector.getApplicationQosPolicyRequestHandler())
633                 .thenReturn(mApplicationQosPolicyRequestHandler);
634 
635         doAnswer(new AnswerWithArguments() {
636             public void answer(Runnable onStoppedListener) throws Throwable {
637                 onStoppedListener.run();
638             }
639         }).when(mMakeBeforeBreakManager).stopAllSecondaryTransientClientModeManagers(any());
640 
641         mWifiServiceImpl = makeWifiServiceImpl();
642         mDppCallback = new IDppCallback() {
643             @Override
644             public void onSuccessConfigReceived(int newNetworkId) throws RemoteException {
645 
646             }
647 
648             @Override
649             public void onSuccess(int status) throws RemoteException {
650 
651             }
652 
653             @Override
654             public void onFailure(int status, String ssid, String channelList, int[] bandList)
655                     throws RemoteException {
656 
657             }
658 
659             @Override
660             public void onProgress(int status) throws RemoteException {
661 
662             }
663 
664             @Override
665             public void onBootstrapUriGenerated(String uri) throws RemoteException {
666 
667             }
668 
669             @Override
670             public IBinder asBinder() {
671                 return null;
672             }
673         };
674 
675         // permission not granted by default
676         doThrow(SecurityException.class).when(mContext).enforceCallingOrSelfPermission(
677                 eq(Manifest.permission.NETWORK_SETUP_WIZARD), any());
678         mTestSoftApInfo = new SoftApInfo();
679         mTestSoftApInfo.setFrequency(TEST_AP_FREQUENCY);
680         mTestSoftApInfo.setBandwidth(TEST_AP_BANDWIDTH);
681         mTestSoftApInfo.setApInstanceIdentifier(WIFI_IFACE_NAME);
682         when(mWifiNative.getChannelsForBand(anyInt())).thenReturn(new int[0]);
683 
684         mTestSoftApInfoList = new ArrayList<>();
685         mTestSoftApInfoList.add(mTestSoftApInfo);
686 
687         mTestSoftApClients = new HashMap<>();
688         mTestSoftApClients.put(WIFI_IFACE_NAME, new ArrayList<WifiClient>());
689         mTestSoftApInfos = new HashMap<>();
690         mTestSoftApInfos.put(WIFI_IFACE_NAME, mTestSoftApInfo);
691 
692         mWifiConfig = new WifiConfiguration();
693         mWifiConfig.SSID = TEST_SSID;
694         mWifiConfig.networkId = TEST_NETWORK_ID;
695 
696         mWifiThreadRunner.prepareForAutoDispatch();
697         setup24GhzSupported();
698     }
699 
700     /**
701      * Called after each test
702      */
703     @After
cleanup()704     public void cleanup() {
705         validateMockitoUsage();
706         if (mSession != null) {
707             mSession.finishMocking();
708         }
709     }
710 
stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(TestLooper looper)711     private void stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(TestLooper looper) {
712         looper.dispatchAll();
713         looper.stopAutoDispatchAndIgnoreExceptions();
714     }
715 
makeWifiServiceImpl()716     private WifiServiceImpl makeWifiServiceImpl() {
717         WifiServiceImpl wifiServiceImpl =
718                 new WifiServiceImpl(mContext, mWifiInjector);
719         ArgumentCaptor<SoftApCallbackInternal> softApCallbackCaptor =
720                 ArgumentCaptor.forClass(SoftApCallbackInternal.class);
721         verify(mActiveModeWarden, atLeastOnce()).registerSoftApCallback(
722                 softApCallbackCaptor.capture());
723         mStateMachineSoftApCallback = softApCallbackCaptor.getValue();
724         ArgumentCaptor<SoftApCallbackInternal> lohsCallbackCaptor =
725                 ArgumentCaptor.forClass(SoftApCallbackInternal.class);
726         mLohsInterfaceName = WIFI_IFACE_NAME;
727         verify(mActiveModeWarden, atLeastOnce()).registerLohsCallback(
728                 lohsCallbackCaptor.capture());
729         mLohsApCallback = lohsCallbackCaptor.getValue();
730         mLooper.dispatchAll();
731         return wifiServiceImpl;
732     }
733 
makeWifiServiceImplWithMockRunnerWhichTimesOut()734     private WifiServiceImpl makeWifiServiceImplWithMockRunnerWhichTimesOut() {
735         WifiThreadRunner mockRunner = mock(WifiThreadRunner.class);
736         when(mockRunner.call(any(), any())).then(returnsSecondArg());
737         when(mockRunner.call(any(), any(int.class))).then(returnsSecondArg());
738         when(mockRunner.call(any(), any(boolean.class))).then(returnsSecondArg());
739         when(mockRunner.post(any())).thenReturn(false);
740 
741         when(mWifiInjector.getWifiThreadRunner()).thenReturn(mockRunner);
742         // Reset mWifiCountryCode to avoid verify failure in makeWifiServiceImpl.
743         reset(mWifiCountryCode);
744         return makeWifiServiceImpl();
745     }
746 
747     /**
748      * Test that REMOVE_NETWORK returns failure to public API when WifiConfigManager returns
749      * failure.
750      */
751     @Test
testRemoveNetworkFailureAppBelowQSdk()752     public void testRemoveNetworkFailureAppBelowQSdk() {
753         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
754                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME,
755                         TEST_FEATURE_ID, null);
756         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
757                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
758         when(mWifiConfigManager.removeNetwork(anyInt(), anyInt(), anyString())).thenReturn(false);
759 
760         mLooper.startAutoDispatch();
761         boolean succeeded = mWifiServiceImpl.removeNetwork(0, TEST_PACKAGE_NAME);
762         mLooper.stopAutoDispatchAndIgnoreExceptions();
763         assertFalse(succeeded);
764     }
765 
766     /**
767      * Ensure WifiMetrics.dump() is the only dump called when 'dumpsys wifi WifiMetricsProto' is
768      * called. This is required to support simple metrics collection via dumpsys
769      */
770     @Test
testWifiMetricsDump()771     public void testWifiMetricsDump() {
772         mWifiServiceImpl.checkAndStartWifi();
773         mLooper.dispatchAll();
774         verify(mWifiMetrics).start();
775         mWifiServiceImpl.dump(new FileDescriptor(), new PrintWriter(new StringWriter()),
776                 new String[]{mWifiMetrics.PROTO_DUMP_ARG});
777         mLooper.dispatchAll();
778         verify(mWifiMetrics).setNonPersistentMacRandomizationForceEnabled(anyBoolean());
779         verify(mWifiMetrics).setIsScanningAlwaysEnabled(anyBoolean());
780         verify(mWifiMetrics).setVerboseLoggingEnabled(anyBoolean());
781         verify(mWifiMetrics)
782                 .dump(any(FileDescriptor.class), any(PrintWriter.class), any(String[].class));
783         verify(mClientModeManager, never())
784                 .dump(any(FileDescriptor.class), any(PrintWriter.class), any(String[].class));
785     }
786 
787     /**
788      * Ensure WifiServiceImpl.dump() doesn't throw an NPE when executed with null args
789      */
790     @Test
testDumpNullArgs()791     public void testDumpNullArgs() {
792         mWifiServiceImpl.checkAndStartWifi();
793         mLooper.dispatchAll();
794         mWifiServiceImpl.dump(new FileDescriptor(), new PrintWriter(new StringWriter()), null);
795         mLooper.dispatchAll();
796         verify(mWifiDiagnostics).captureBugReportData(
797                 WifiDiagnostics.REPORT_REASON_USER_ACTION);
798         verify(mWifiDiagnostics).dump(any(), any(), any());
799     }
800 
801     @Test
testWifiShellCommandIgnoredBeforeBoot()802     public void testWifiShellCommandIgnoredBeforeBoot() {
803         // verify shell command can't be called before boot complete
804         ParcelFileDescriptor mockDescriptor = mock(ParcelFileDescriptor.class);
805         assertEquals(-1, mWifiServiceImpl.handleShellCommand(mockDescriptor,
806                 mockDescriptor, mockDescriptor, new String[0]));
807 
808         // verify shell command can now be called after boot complete
809         mWifiServiceImpl.handleBootCompleted();
810         mLooper.dispatchAll();
811         assertEquals(0, mWifiServiceImpl.handleShellCommand(mockDescriptor,
812                 mockDescriptor, mockDescriptor, new String[0]));
813     }
814 
815     /**
816      * Verify that metrics is incremented correctly for Privileged Apps.
817      */
818     @Test
testSetWifiEnabledMetricsPrivilegedApp()819     public void testSetWifiEnabledMetricsPrivilegedApp() throws Exception {
820         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
821                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
822         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
823         when(mSettingsStore.handleWifiToggled(anyBoolean())).thenReturn(true);
824         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
825         when(mWakeupController.isUsable()).thenReturn(false);
826 
827         InOrder inorder = inOrder(mWifiMetrics);
828         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
829         mLooper.dispatchAll();
830         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
831         mLooper.dispatchAll();
832         verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, false);
833         inorder.verify(mWifiMetrics).logUserActionEvent(UserActionEvent.EVENT_TOGGLE_WIFI_ON);
834         inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(true), eq(true));
835         inorder.verify(mWifiMetrics).reportWifiStateChanged(true, false, false);
836         inorder.verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_TOGGLE_WIFI_OFF),
837                 anyInt());
838         inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(true), eq(false));
839         inorder.verify(mWifiMetrics).reportWifiStateChanged(false, false, false);
840         verify(mLastCallerInfoManager).put(eq(WifiManager.API_WIFI_ENABLED), anyInt(),
841                 anyInt(), anyInt(), anyString(), eq(false));
842     }
843 
844     /**
845      * Verify that metrics is incremented correctly for normal Apps targeting pre-Q.
846      */
847     @Test
testSetWifiEnabledMetricsNormalAppBelowQSdk()848     public void testSetWifiEnabledMetricsNormalAppBelowQSdk() throws Exception {
849         when(mWifiSettingsConfigStore.get(
850                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)))
851                 .thenReturn(false);
852         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
853                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
854         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
855                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
856         when(mSettingsStore.handleWifiToggled(anyBoolean())).thenReturn(true);
857         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
858         when(mWakeupController.isUsable()).thenReturn(true);
859 
860         InOrder inorder = inOrder(mWifiMetrics);
861         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
862         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
863         inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(false), eq(true));
864         inorder.verify(mWifiMetrics).reportWifiStateChanged(true, true, false);
865         inorder.verify(mWifiMetrics).incrementNumWifiToggles(eq(false), eq(false));
866         inorder.verify(mWifiMetrics).reportWifiStateChanged(false, true, false);
867     }
868 
869     /**
870      * Verify that metrics is not incremented by apps targeting Q SDK.
871      */
872     @Test
testSetWifiEnabledMetricsNormalAppTargetingQSdkNoIncrement()873     public void testSetWifiEnabledMetricsNormalAppTargetingQSdkNoIncrement() throws Exception {
874         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
875                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
876         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
877                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
878         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
879         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
880 
881         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
882         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
883         verify(mWifiMetrics, never()).incrementNumWifiToggles(anyBoolean(), anyBoolean());
884         verify(mWifiMetrics, never()).reportWifiStateChanged(anyBoolean(), anyBoolean(),
885                 anyBoolean());
886     }
887 
888     /**
889      * Verify that wifi can be enabled by a caller with NETWORK_SETTINGS permission.
890      */
891     @Test
testSetWifiEnabledSuccessWithNetworkSettingsPermission()892     public void testSetWifiEnabledSuccessWithNetworkSettingsPermission() throws Exception {
893         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
894                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
895         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
896         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
897         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
898         verify(mActiveModeWarden).wifiToggled(
899                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
900     }
901 
902     /**
903      * Verify that wifi can be enabled by a caller with NETWORK_MANAGED_PROVISIONING permission.
904      */
905     @Test
testSetWifiEnabledSuccessWithNetworkManagedProvisioningPermission()906     public void testSetWifiEnabledSuccessWithNetworkManagedProvisioningPermission()
907             throws Exception {
908         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_MANAGED_PROVISIONING),
909                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
910         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
911         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
912         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
913         verify(mActiveModeWarden).wifiToggled(
914                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
915     }
916 
917     /**
918      * Verify that wifi can be enabled by the DO apps targeting Q SDK.
919      */
920     @Test
testSetWifiEnabledSuccessForDOAppsTargetingQSdk()921     public void testSetWifiEnabledSuccessForDOAppsTargetingQSdk() throws Exception {
922         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
923                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
924         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
925                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
926         when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
927                 .thenReturn(true);
928 
929         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
930         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
931         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
932 
933         verify(mActiveModeWarden).wifiToggled(
934                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
935     }
936 
937     /**
938      * Verify that wifi can be enabled by the system apps targeting Q SDK.
939      */
940     @Test
testSetWifiEnabledSuccessForSystemAppsTargetingQSdk()941     public void testSetWifiEnabledSuccessForSystemAppsTargetingQSdk() throws Exception {
942         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
943                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
944         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
945                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
946         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
947 
948         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
949         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
950         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
951 
952         verify(mActiveModeWarden).wifiToggled(
953                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
954     }
955 
956     /**
957      * Verify that wifi can be enabled by the apps targeting pre-Q SDK.
958      */
959     @Test
testSetWifiEnabledSuccessForAppsTargetingBelowQSdk()960     public void testSetWifiEnabledSuccessForAppsTargetingBelowQSdk() throws Exception {
961         when(mWifiSettingsConfigStore.get(
962                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)))
963                 .thenReturn(false);
964         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
965                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
966         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
967                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
968 
969         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
970         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
971         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
972 
973         verify(mActiveModeWarden).wifiToggled(
974                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
975     }
976 
977     /**
978      * Verify that wifi cannot be enabled by the apps targeting Q SDK.
979      */
980     @Test
testSetWifiEnabledFailureForAppsTargetingQSdk()981     public void testSetWifiEnabledFailureForAppsTargetingQSdk() throws Exception {
982         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
983                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
984         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
985                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
986 
987         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
988         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
989         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
990 
991         verify(mActiveModeWarden, never()).wifiToggled(any());
992     }
993 
994     /**
995      * Verify a SecurityException is thrown if OPSTR_CHANGE_WIFI_STATE is disabled for the app.
996      */
997     @Test
testSetWifiEnableAppOpsRejected()998     public void testSetWifiEnableAppOpsRejected() throws Exception {
999         doThrow(new SecurityException()).when(mAppOpsManager)
1000                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1001         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1002                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1003         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1004         try {
1005             mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true);
1006             fail();
1007         } catch (SecurityException e) {
1008 
1009         }
1010         verify(mActiveModeWarden, never()).wifiToggled(any());
1011     }
1012 
1013     /**
1014      * Verify a SecurityException is thrown if OP_CHANGE_WIFI_STATE is set to MODE_IGNORED
1015      * for the app.
1016      */
1017     @Test // No exception expected, but the operation should not be done
testSetWifiEnableAppOpsIgnored()1018     public void testSetWifiEnableAppOpsIgnored() throws Exception {
1019         doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager)
1020                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1021         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1022                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1023         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1024 
1025         mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true);
1026         verify(mActiveModeWarden, never()).wifiToggled(any());
1027     }
1028 
1029     /**
1030      * Verify that a call from an app with the NETWORK_SETTINGS permission can enable wifi if we
1031      * are in airplane mode.
1032      */
1033     @Test
testSetWifiEnabledFromNetworkSettingsHolderWhenInAirplaneMode()1034     public void testSetWifiEnabledFromNetworkSettingsHolderWhenInAirplaneMode() throws Exception {
1035         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1036         when(mSettingsStore.isAirplaneModeOn()).thenReturn(true);
1037         when(mContext.checkPermission(
1038                 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
1039                 .thenReturn(PackageManager.PERMISSION_GRANTED);
1040 
1041         assertTrue(mWifiServiceImpl.setWifiEnabled(SYSUI_PACKAGE_NAME, true));
1042         verify(mActiveModeWarden).wifiToggled(
1043                 eq(new WorkSource(Binder.getCallingUid(), SYSUI_PACKAGE_NAME)));
1044     }
1045 
1046     /**
1047      * Verify that a caller without the NETWORK_SETTINGS permission can't enable wifi
1048      * if we are in airplane mode.
1049      */
1050     @Test
testSetWifiEnabledFromAppFailsWhenInAirplaneMode()1051     public void testSetWifiEnabledFromAppFailsWhenInAirplaneMode() throws Exception {
1052         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1053                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1054         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1055                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1056         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1057         when(mSettingsStore.isAirplaneModeOn()).thenReturn(true);
1058         when(mContext.checkPermission(
1059                 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
1060                 .thenReturn(PackageManager.PERMISSION_DENIED);
1061 
1062         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1063         verify(mActiveModeWarden, never()).wifiToggled(any());
1064     }
1065 
1066     /**
1067      * Verify that a user (NETWORK_SETTINGS) cannot enable wifi if DISALLOW_CHANGE_WIFI_STATE
1068      * user restriction is set.
1069      */
1070     @Test
testSetWifiEnabledFromUserFailsWhenUserRestrictionSet()1071     public void testSetWifiEnabledFromUserFailsWhenUserRestrictionSet() throws Exception {
1072         assumeTrue(SdkLevel.isAtLeastT());
1073         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
1074                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1075 
1076         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1077         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1078         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CHANGE_WIFI_STATE),
1079                 any())).thenReturn(true);
1080 
1081         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1082         verify(mActiveModeWarden, never()).wifiToggled(any());
1083     }
1084 
1085     /**
1086      * Verify that apps targeting pre-Q SDK cannot enable wifi if DISALLOW_CHANGE_WIFI_STATE
1087      * user restriction is set.
1088      */
1089     @Test
testSetWifiEnabledFromAppTargetingBelowQSdkFailsWhenUserRestrictionSet()1090     public void testSetWifiEnabledFromAppTargetingBelowQSdkFailsWhenUserRestrictionSet()
1091             throws Exception {
1092         assumeTrue(SdkLevel.isAtLeastT());
1093         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1094                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1095         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1096                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1097 
1098         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1099         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1100         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CHANGE_WIFI_STATE),
1101                 any())).thenReturn(true);
1102 
1103         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1104         verify(mActiveModeWarden, never()).wifiToggled(any());
1105     }
1106 
1107     /**
1108      * Verify that wifi can be enabled by the DO apps even when DISALLOW_CHANGE_WIFI_STATE
1109      * user restriction is set.
1110      */
1111     @Test
testSetWifiEnabledSuccessForDOAppsWhenUserRestrictionSet()1112     public void testSetWifiEnabledSuccessForDOAppsWhenUserRestrictionSet() throws Exception {
1113         assumeTrue(SdkLevel.isAtLeastT());
1114         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1115                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1116         when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
1117                 .thenReturn(true);
1118 
1119         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1120         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1121         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CHANGE_WIFI_STATE),
1122                 any())).thenReturn(true);
1123 
1124         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1125         verify(mActiveModeWarden).wifiToggled(
1126                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1127     }
1128 
1129     /**
1130      * Verify that a dialog is shown for third-party apps targeting pre-Q SDK enabling Wi-Fi.
1131      */
1132     @Test
testSetWifiEnabledDialogForThirdPartyAppsTargetingBelowQSdk()1133     public void testSetWifiEnabledDialogForThirdPartyAppsTargetingBelowQSdk() throws Exception {
1134         when(mWifiSettingsConfigStore.get(
1135                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)))
1136                 .thenReturn(false);
1137         when(mResources.getBoolean(
1138                 R.bool.config_showConfirmationDialogForThirdPartyAppsEnablingWifi))
1139                 .thenReturn(true);
1140         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1141                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1142         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1143                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1144         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1145         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1146         ApplicationInfo applicationInfo = mock(ApplicationInfo.class);
1147         when(mPackageManager.getApplicationInfo(any(), anyInt())).thenReturn(applicationInfo);
1148         String appName = "appName";
1149         when(applicationInfo.loadLabel(any())).thenReturn(appName);
1150         String title = "appName wants to enable Wi-Fi.";
1151         String message = "Enable Wi-Fi?";
1152         String positiveButtonText = "Yes";
1153         String negativeButtonText = "No";
1154         when(mResources.getString(R.string.wifi_enable_request_dialog_title, appName))
1155                 .thenReturn(title);
1156         when(mResources.getString(R.string.wifi_enable_request_dialog_message)).thenReturn(message);
1157         when(mResources.getString(R.string.wifi_enable_request_dialog_positive_button))
1158                 .thenReturn(positiveButtonText);
1159         when(mResources.getString(R.string.wifi_enable_request_dialog_negative_button))
1160                 .thenReturn(negativeButtonText);
1161 
1162         // Verify the negative reply does not enable wifi
1163         WifiDialogManager.DialogHandle dialogHandle = mock(WifiDialogManager.DialogHandle.class);
1164         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
1165                 .thenReturn(dialogHandle);
1166         ArgumentCaptor<WifiDialogManager.SimpleDialogCallback> callbackCaptor =
1167                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
1168         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1169         verify(mActiveModeWarden, times(0)).wifiToggled(
1170                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1171         mLooper.dispatchAll();
1172         verify(mWifiDialogManager, times(1)).createSimpleDialog(
1173                 eq(title),
1174                 eq(message),
1175                 eq(positiveButtonText),
1176                 eq(negativeButtonText),
1177                 eq(null),
1178                 callbackCaptor.capture(),
1179                 any());
1180         verify(dialogHandle).launchDialog();
1181         callbackCaptor.getValue().onNegativeButtonClicked();
1182         verify(mActiveModeWarden, times(0)).wifiToggled(
1183                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1184 
1185         // Verify the cancel reply does not enable wifi.
1186         dialogHandle = mock(WifiDialogManager.DialogHandle.class);
1187         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
1188                 .thenReturn(dialogHandle);
1189         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1190         mLooper.dispatchAll();
1191         verify(mActiveModeWarden, times(0)).wifiToggled(
1192                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1193         callbackCaptor =
1194                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
1195         verify(mWifiDialogManager, times(2)).createSimpleDialog(
1196                 eq(title),
1197                 eq(message),
1198                 eq(positiveButtonText),
1199                 eq(negativeButtonText),
1200                 eq(null),
1201                 callbackCaptor.capture(),
1202                 any());
1203         verify(dialogHandle).launchDialog();
1204         callbackCaptor.getValue().onCancelled();
1205         verify(mActiveModeWarden, times(0)).wifiToggled(
1206                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1207 
1208         // Verify the positive reply will enable wifi.
1209         dialogHandle = mock(WifiDialogManager.DialogHandle.class);
1210         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
1211                 .thenReturn(dialogHandle);
1212         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1213         mLooper.dispatchAll();
1214         verify(mActiveModeWarden, times(0)).wifiToggled(
1215                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1216         callbackCaptor =
1217                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
1218         verify(mWifiDialogManager, times(3)).createSimpleDialog(
1219                 eq(title),
1220                 eq(message),
1221                 eq(positiveButtonText),
1222                 eq(negativeButtonText),
1223                 eq(null),
1224                 callbackCaptor.capture(),
1225                 any());
1226         verify(dialogHandle).launchDialog();
1227         callbackCaptor.getValue().onPositiveButtonClicked();
1228         verify(mActiveModeWarden, times(1)).wifiToggled(
1229                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1230 
1231         // Verify disabling wifi works without dialog.
1232         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1233         dialogHandle = mock(WifiDialogManager.DialogHandle.class);
1234         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
1235                 .thenReturn(dialogHandle);
1236         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1237         mLooper.dispatchAll();
1238         verify(mActiveModeWarden, times(2)).wifiToggled(
1239                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1240         verify(dialogHandle, never()).launchDialog();
1241 
1242         // Verify wifi becoming enabled will dismiss any outstanding dialogs.
1243         dialogHandle = mock(WifiDialogManager.DialogHandle.class);
1244         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
1245                 .thenReturn(dialogHandle);
1246         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1247         mLooper.dispatchAll();
1248         verify(mActiveModeWarden, times(2)).wifiToggled(
1249                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1250         callbackCaptor =
1251                 ArgumentCaptor.forClass(WifiDialogManager.SimpleDialogCallback.class);
1252         verify(mWifiDialogManager, times(4)).createSimpleDialog(
1253                 eq(title),
1254                 eq(message),
1255                 eq(positiveButtonText),
1256                 eq(negativeButtonText),
1257                 eq(null),
1258                 callbackCaptor.capture(),
1259                 any());
1260         verify(dialogHandle).launchDialog();
1261         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
1262         // Enabled by privileged app
1263         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1264         mLooper.dispatchAll();
1265         verify(mActiveModeWarden, times(3)).wifiToggled(
1266                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1267         verify(dialogHandle).dismissDialog();
1268 
1269         // Verify wifi already enabled will not trigger dialog.
1270         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(false);
1271         dialogHandle = mock(WifiDialogManager.DialogHandle.class);
1272         when(mWifiDialogManager.createSimpleDialog(any(), any(), any(), any(), any(), any(), any()))
1273                 .thenReturn(dialogHandle);
1274         when(mActiveModeWarden.getWifiState()).thenReturn(WifiManager.WIFI_STATE_ENABLED);
1275         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1276         mLooper.dispatchAll();
1277         verify(mActiveModeWarden, times(3)).wifiToggled(
1278                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1279         verify(dialogHandle, never()).launchDialog();
1280     }
1281 
1282     /**
1283      * Verify that no dialog is shown for non-third-party apps targeting pre-Q SDK enabling Wi-Fi.
1284      */
1285     @Test
testSetWifiEnabledNoDialogForNonThirdPartyAppsTargetingBelowQSdk()1286     public void testSetWifiEnabledNoDialogForNonThirdPartyAppsTargetingBelowQSdk() {
1287         when(mWifiSettingsConfigStore.get(
1288                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)))
1289                 .thenReturn(false);
1290         when(mResources.getBoolean(
1291                 R.bool.config_showConfirmationDialogForThirdPartyAppsEnablingWifi))
1292                 .thenReturn(true);
1293         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1294                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1295         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1296                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1297         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1298         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1299         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
1300 
1301         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1302         verify(mActiveModeWarden).wifiToggled(
1303                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1304     }
1305 
1306     /**
1307      * Helper to verify registering for state changes.
1308      */
verifyApRegistration()1309     private void verifyApRegistration() {
1310         assertNotNull(mLohsApCallback);
1311     }
1312 
1313     /**
1314      * Helper to emulate local-only hotspot state changes.
1315      *
1316      * Must call verifyApRegistration first.
1317      */
changeLohsState(int apState, int previousState, int error)1318     private void changeLohsState(int apState, int previousState, int error) {
1319         // TestUtil.sendWifiApStateChanged(mBroadcastReceiverCaptor.getValue(), mContext,
1320         //        apState, previousState, error, WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
1321         mLohsApCallback.onStateChanged(apState, error);
1322     }
1323 
1324     /**
1325      * Verify that a call from an app with the NETWORK_SETTINGS permission can enable wifi if we
1326      * are in softap mode.
1327      */
1328     @Test
testSetWifiEnabledFromNetworkSettingsHolderWhenApEnabled()1329     public void testSetWifiEnabledFromNetworkSettingsHolderWhenApEnabled() throws Exception {
1330         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1331         mWifiServiceImpl.checkAndStartWifi();
1332         mLooper.dispatchAll();
1333 
1334         verifyApRegistration();
1335         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
1336 
1337         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(true);
1338         when(mContext.checkPermission(
1339                 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
1340                 .thenReturn(PackageManager.PERMISSION_GRANTED);
1341         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1342         assertTrue(mWifiServiceImpl.setWifiEnabled(SYSUI_PACKAGE_NAME, true));
1343         verify(mActiveModeWarden).wifiToggled(
1344                 eq(new WorkSource(Binder.getCallingUid(), SYSUI_PACKAGE_NAME)));
1345     }
1346 
1347     /**
1348      * Verify that a call from an app cannot enable wifi if we are in softap mode.
1349      */
1350     @Test
testSetWifiEnabledFromAppFailsWhenApEnabled()1351     public void testSetWifiEnabledFromAppFailsWhenApEnabled() throws Exception {
1352         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1353                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1354         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1355                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1356         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1357         mWifiServiceImpl.checkAndStartWifi();
1358         mLooper.dispatchAll();
1359 
1360         verifyApRegistration();
1361         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
1362 
1363         when(mContext.checkPermission(
1364                 eq(android.Manifest.permission.NETWORK_SETTINGS), anyInt(), anyInt()))
1365                 .thenReturn(PackageManager.PERMISSION_DENIED);
1366         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1367         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1368         verify(mSettingsStore, never()).handleWifiToggled(anyBoolean());
1369         verify(mActiveModeWarden, never()).wifiToggled(any());
1370     }
1371 
1372 
1373     /**
1374      * Verify that the CMD_TOGGLE_WIFI message won't be sent if wifi is already on.
1375      */
1376     @Test
testSetWifiEnabledNoToggle()1377     public void testSetWifiEnabledNoToggle() throws Exception {
1378         when(mSettingsStore.handleWifiToggled(eq(true))).thenReturn(false);
1379         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
1380                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1381         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
1382         verify(mActiveModeWarden, never()).wifiToggled(any());
1383     }
1384 
1385     /**
1386      * Verify a SecurityException is thrown if a caller does not have the CHANGE_WIFI_STATE
1387      * permission to toggle wifi.
1388      */
1389     @Test
testSetWifiEnableWithoutChangeWifiStatePermission()1390     public void testSetWifiEnableWithoutChangeWifiStatePermission() throws Exception {
1391         doThrow(new SecurityException()).when(mContext)
1392                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.CHANGE_WIFI_STATE),
1393                                                 eq("WifiService"));
1394         try {
1395             mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true);
1396             fail();
1397         } catch (SecurityException e) {
1398         }
1399     }
1400 
1401     /**
1402      * Verify that wifi can be disabled by a caller with NETWORK_SETTINGS permission.
1403      */
1404     @Test
testSetWifiDisabledSuccessWithNetworkSettingsPermission()1405     public void testSetWifiDisabledSuccessWithNetworkSettingsPermission() throws Exception {
1406         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
1407                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1408         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1409         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1410         verify(mActiveModeWarden).wifiToggled(
1411                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1412         verify(mInterfaceConflictManager).reset();
1413     }
1414 
1415     /**
1416      * Verify that wifi can be disabled by a caller with NETWORK_MANAGED_PROVISIONING permission.
1417      */
1418     @Test
testSetWifiDisabledSuccessWithNetworkManagedProvisioningPermission()1419     public void testSetWifiDisabledSuccessWithNetworkManagedProvisioningPermission()
1420             throws Exception {
1421         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_MANAGED_PROVISIONING),
1422                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1423         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1424         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1425         verify(mActiveModeWarden).wifiToggled(
1426                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1427         verify(mInterfaceConflictManager).reset();
1428     }
1429 
1430     /**
1431      * Verify that wifi can be disabled by the PO apps targeting Q SDK.
1432      */
1433     @Test
testSetWifiDisabledSuccessForPOAppsTargetingQSdk()1434     public void testSetWifiDisabledSuccessForPOAppsTargetingQSdk() throws Exception {
1435         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1436                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1437         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1438                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
1439         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
1440                 .thenReturn(true);
1441 
1442         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1443         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1444         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1445 
1446         verify(mActiveModeWarden).wifiToggled(
1447                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1448         verify(mInterfaceConflictManager).reset();
1449     }
1450 
1451     /**
1452      * Verify that wifi can be disabled by the system apps targeting Q SDK.
1453      */
1454     @Test
testSetWifiDisabledSuccessForSystemAppsTargetingQSdk()1455     public void testSetWifiDisabledSuccessForSystemAppsTargetingQSdk() throws Exception {
1456         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1457                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1458         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1459                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
1460         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
1461 
1462         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1463         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1464         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1465 
1466         verify(mActiveModeWarden).wifiToggled(
1467                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1468         verify(mInterfaceConflictManager).reset();
1469     }
1470 
1471 
1472     /**
1473      * Verify that wifi can be disabled by the apps targeting pre-Q SDK.
1474      */
1475     @Test
testSetWifiDisabledSuccessForAppsTargetingBelowQSdk()1476     public void testSetWifiDisabledSuccessForAppsTargetingBelowQSdk() throws Exception {
1477         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1478                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1479         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1480                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
1481 
1482         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1483         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1484         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1485 
1486         verify(mActiveModeWarden).wifiToggled(
1487                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
1488         verify(mInterfaceConflictManager).reset();
1489     }
1490 
1491     /**
1492      * Verify that wifi cannot be disabled by the apps targeting Q SDK.
1493      */
1494     @Test
testSetWifiDisabledFailureForAppsTargetingQSdk()1495     public void testSetWifiDisabledFailureForAppsTargetingQSdk() throws Exception {
1496         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
1497                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
1498         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
1499                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(false);
1500 
1501         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(true);
1502         when(mSettingsStore.isAirplaneModeOn()).thenReturn(false);
1503         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1504 
1505         verify(mActiveModeWarden, never()).wifiToggled(any());
1506         verify(mInterfaceConflictManager, never()).reset();
1507     }
1508 
1509     /**
1510      * Verify that CMD_TOGGLE_WIFI message won't be sent if wifi is already off.
1511      */
1512     @Test
testSetWifiDisabledNoToggle()1513     public void testSetWifiDisabledNoToggle() throws Exception {
1514         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
1515                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1516         when(mSettingsStore.handleWifiToggled(eq(false))).thenReturn(false);
1517         assertTrue(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false));
1518         verify(mActiveModeWarden, never()).wifiToggled(any());
1519         verify(mInterfaceConflictManager, never()).reset();
1520     }
1521 
1522     /**
1523      * Verify a SecurityException is thrown if a caller does not have the CHANGE_WIFI_STATE
1524      * permission to toggle wifi.
1525      */
1526     @Test
testSetWifiDisabledWithoutChangeWifiStatePermission()1527     public void testSetWifiDisabledWithoutChangeWifiStatePermission() throws Exception {
1528         doThrow(new SecurityException()).when(mContext)
1529                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.CHANGE_WIFI_STATE),
1530                         eq("WifiService"));
1531         try {
1532             mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, false);
1533             fail();
1534         } catch (SecurityException e) { }
1535     }
1536 
1537     /**
1538      * Verify that the restartWifiSubsystem fails w/o the NETWORK_AIRPLANE_MODE permission.
1539      */
testRestartWifiSubsystemWithoutPermission()1540     @Test public void testRestartWifiSubsystemWithoutPermission() {
1541         assumeTrue(SdkLevel.isAtLeastS());
1542         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
1543                 eq(android.Manifest.permission.RESTART_WIFI_SUBSYSTEM), eq("WifiService"));
1544 
1545         try {
1546             mWifiServiceImpl.restartWifiSubsystem();
1547             fail("restartWifiSubsystem should fail w/o the APM permission!");
1548         } catch (SecurityException e) {
1549             // empty clause
1550         }
1551     }
1552 
1553     /**
1554      * Verify that a call to registerSubsystemRestartCallback throws a SecurityException if the
1555      * caller does not have the ACCESS_WIFI_STATE permission.
1556      */
1557     @Test
testRegisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions()1558     public void testRegisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions() {
1559         assumeTrue(SdkLevel.isAtLeastS());
1560         doThrow(new SecurityException()).when(mContext)
1561                 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE),
1562                         eq("WifiService"));
1563         try {
1564             mWifiServiceImpl.registerSubsystemRestartCallback(mSubsystemRestartCallback);
1565             fail("expected SecurityException");
1566         } catch (SecurityException expected) { }
1567     }
1568 
1569     /**
1570      * Verify that a call to unregisterSubsystemRestartCallback throws a SecurityException if the
1571      * caller does not have the ACCESS_WIFI_STATE permission.
1572      */
1573     @Test
testUnregisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions()1574     public void testUnregisterSubsystemRestartThrowsSecurityExceptionOnMissingPermissions() {
1575         assumeTrue(SdkLevel.isAtLeastS());
1576         doThrow(new SecurityException()).when(mContext)
1577                 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE),
1578                         eq("WifiService"));
1579         try {
1580             mWifiServiceImpl.unregisterSubsystemRestartCallback(mSubsystemRestartCallback);
1581             fail("expected SecurityException");
1582         } catch (SecurityException expected) { }
1583     }
1584 
1585 
1586     /**
1587      * Test register and unregister subsystem restart callback will go to ActiveModeManager;
1588      */
1589     @Test
testRegisterUnregisterSubsystemRestartCallback()1590     public void testRegisterUnregisterSubsystemRestartCallback() throws Exception {
1591         assumeTrue(SdkLevel.isAtLeastS());
1592         when(mCoexCallback.asBinder()).thenReturn(mAppBinder);
1593         mWifiServiceImpl.registerSubsystemRestartCallback(mSubsystemRestartCallback);
1594         mLooper.dispatchAll();
1595         verify(mActiveModeWarden).registerSubsystemRestartCallback(mSubsystemRestartCallback);
1596         mWifiServiceImpl.unregisterSubsystemRestartCallback(mSubsystemRestartCallback);
1597         mLooper.dispatchAll();
1598         verify(mActiveModeWarden).unregisterSubsystemRestartCallback(mSubsystemRestartCallback);
1599     }
1600 
1601     @Test
testAddWifiNetworkStateChangedListener()1602     public void testAddWifiNetworkStateChangedListener() throws Exception {
1603         IWifiNetworkStateChangedListener testListener =
1604                 mock(IWifiNetworkStateChangedListener.class);
1605 
1606         // Test success case
1607         mWifiServiceImpl.addWifiNetworkStateChangedListener(testListener);
1608         mLooper.dispatchAll();
1609         verify(mActiveModeWarden).addWifiNetworkStateChangedListener(testListener);
1610 
1611         // Expect exception for null listener
1612         assertThrows(IllegalArgumentException.class,
1613                 () -> mWifiServiceImpl.addWifiNetworkStateChangedListener(null));
1614 
1615         // Expect exception when caller has no permission
1616         doThrow(new SecurityException()).when(mContext)
1617                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
1618                         eq("WifiService"));
1619         assertThrows(SecurityException.class,
1620                 () -> mWifiServiceImpl.addWifiNetworkStateChangedListener(testListener));
1621         verify(mActiveModeWarden).addWifiNetworkStateChangedListener(testListener);
1622     }
1623 
1624     /**
1625      * Verify that the restartWifiSubsystem succeeds and passes correct parameters.
1626      */
1627     @Test
testRestartWifiSubsystem()1628     public void testRestartWifiSubsystem() {
1629         assumeTrue(SdkLevel.isAtLeastS());
1630         when(mContext.checkPermission(eq(android.Manifest.permission.RESTART_WIFI_SUBSYSTEM),
1631                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1632 
1633         mWifiServiceImpl.restartWifiSubsystem();
1634         mLooper.dispatchAll();
1635         verify(mSelfRecovery).trigger(eq(REASON_API_CALL));
1636         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_RESTART_WIFI_SUB_SYSTEM),
1637                 anyInt());
1638     }
1639 
1640     /**
1641      * Ensure unpermitted callers cannot write the SoftApConfiguration.
1642      */
1643     @Test
testSetWifiApConfigurationNotSavedWithoutPermission()1644     public void testSetWifiApConfigurationNotSavedWithoutPermission() throws Exception {
1645         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false);
1646         WifiConfiguration apConfig = new WifiConfiguration();
1647         try {
1648             mWifiServiceImpl.setWifiApConfiguration(apConfig, TEST_PACKAGE_NAME);
1649             fail("Expected SecurityException");
1650         } catch (SecurityException e) { }
1651     }
1652 
1653     /**
1654      * Ensure softap config is written when the caller has the correct permission.
1655      */
1656     @Test
testSetWifiApConfigurationSuccess()1657     public void testSetWifiApConfigurationSuccess() throws Exception {
1658         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1659         WifiConfiguration wifiApConfig = createValidWifiApConfiguration();
1660 
1661         assertTrue(mWifiServiceImpl.setWifiApConfiguration(wifiApConfig, TEST_PACKAGE_NAME));
1662         mLooper.dispatchAll();
1663         verifyCheckChangePermission(TEST_PACKAGE_NAME);
1664         verify(mWifiApConfigStore).setApConfiguration(eq(
1665                 ApConfigUtil.fromWifiConfiguration(wifiApConfig)));
1666     }
1667 
1668     /**
1669      * Ensure that a null config does not overwrite the saved ap config.
1670      */
1671     @Test
testSetWifiApConfigurationNullConfigNotSaved()1672     public void testSetWifiApConfigurationNullConfigNotSaved() throws Exception {
1673         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1674         assertFalse(mWifiServiceImpl.setWifiApConfiguration(null, TEST_PACKAGE_NAME));
1675         verify(mWifiApConfigStore, never()).setApConfiguration(isNull(SoftApConfiguration.class));
1676     }
1677 
1678     /**
1679      * Ensure that an invalid config does not overwrite the saved ap config.
1680      */
1681     @Test
testSetWifiApConfigurationWithInvalidConfigNotSaved()1682     public void testSetWifiApConfigurationWithInvalidConfigNotSaved() throws Exception {
1683         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1684         assertFalse(mWifiServiceImpl.setWifiApConfiguration(new WifiConfiguration(),
1685                                                             TEST_PACKAGE_NAME));
1686         verify(mWifiApConfigStore, never()).setApConfiguration(any());
1687     }
1688 
1689     /**
1690      * Ensure unpermitted callers cannot write the SoftApConfiguration.
1691      */
1692     @Test
testSetSoftApConfigurationNotSavedWithoutPermission()1693     public void testSetSoftApConfigurationNotSavedWithoutPermission() throws Exception {
1694         SoftApConfiguration apConfig = createValidSoftApConfiguration();
1695         try {
1696             mWifiServiceImpl.setSoftApConfiguration(apConfig, TEST_PACKAGE_NAME);
1697             fail("Expected SecurityException");
1698         } catch (SecurityException e) { }
1699     }
1700 
1701     /**
1702      * Ensure softap config is written when the caller has the correct permission.
1703      */
1704     @Test
testSetSoftApConfigurationSuccessWithSettingPermission()1705     public void testSetSoftApConfigurationSuccessWithSettingPermission() throws Exception {
1706         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
1707         SoftApConfiguration apConfig = createValidSoftApConfiguration();
1708 
1709         assertTrue(mWifiServiceImpl.setSoftApConfiguration(apConfig, TEST_PACKAGE_NAME));
1710         verify(mWifiApConfigStore).setApConfiguration(eq(apConfig));
1711         verify(mActiveModeWarden).updateSoftApConfiguration(apConfig);
1712         verify(mWifiPermissionsUtil).checkNetworkSettingsPermission(anyInt());
1713     }
1714 
1715     /**
1716      * Ensure softap config is written when the caller has the correct permission.
1717      */
1718     @Test
testSetSoftApConfigurationSuccessWithOverridePermission()1719     public void testSetSoftApConfigurationSuccessWithOverridePermission() throws Exception {
1720         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1721         SoftApConfiguration apConfig = createValidSoftApConfiguration();
1722 
1723         assertTrue(mWifiServiceImpl.setSoftApConfiguration(apConfig, TEST_PACKAGE_NAME));
1724         verify(mWifiApConfigStore).setApConfiguration(eq(apConfig));
1725         verify(mActiveModeWarden).updateSoftApConfiguration(apConfig);
1726         verify(mWifiPermissionsUtil).checkConfigOverridePermission(anyInt());
1727     }
1728 
1729     /**
1730      * Ensure that a null config does not overwrite the saved ap config.
1731      */
1732     @Test
testSetSoftApConfigurationNullConfigNotSaved()1733     public void testSetSoftApConfigurationNullConfigNotSaved() throws Exception {
1734         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1735         assertFalse(mWifiServiceImpl.setSoftApConfiguration(null, TEST_PACKAGE_NAME));
1736         verify(mWifiApConfigStore, never()).setApConfiguration(isNull(SoftApConfiguration.class));
1737         verify(mActiveModeWarden, never()).updateSoftApConfiguration(any());
1738         verify(mWifiPermissionsUtil).checkConfigOverridePermission(anyInt());
1739     }
1740 
1741     /**
1742      * Ensure that an invalid config does not overwrite the saved ap config.
1743      */
1744     @Test
testSetSoftApConfigurationWithInvalidConfigNotSaved()1745     public void testSetSoftApConfigurationWithInvalidConfigNotSaved() throws Exception {
1746         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1747         assertFalse(mWifiServiceImpl.setSoftApConfiguration(
1748                 new SoftApConfiguration.Builder().build(), TEST_PACKAGE_NAME));
1749         verify(mWifiApConfigStore, never()).setApConfiguration(any());
1750         verify(mWifiPermissionsUtil).checkConfigOverridePermission(anyInt());
1751     }
1752 
1753     /**
1754      * Ensure unpermitted callers are not able to retrieve the softap config.
1755      */
1756     @Test
testGetSoftApConfigurationNotReturnedWithoutPermission()1757     public void testGetSoftApConfigurationNotReturnedWithoutPermission() throws Exception {
1758         try {
1759             mWifiServiceImpl.getSoftApConfiguration();
1760             fail("Expected a SecurityException");
1761         } catch (SecurityException e) {
1762         }
1763     }
1764 
1765     /**
1766      * Ensure permitted callers are able to retrieve the softap config.
1767      */
1768     @Test
testGetSoftApConfigurationSuccess()1769     public void testGetSoftApConfigurationSuccess() throws Exception {
1770         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1771         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1772         SoftApConfiguration apConfig = createValidSoftApConfiguration();
1773         when(mWifiApConfigStore.getApConfiguration()).thenReturn(apConfig);
1774 
1775         mLooper.startAutoDispatch();
1776         assertThat(apConfig).isEqualTo(mWifiServiceImpl.getSoftApConfiguration());
1777 
1778         mLooper.stopAutoDispatchAndIgnoreExceptions();
1779     }
1780 
1781     /**
1782      * Ensure unpermitted callers are not able to retrieve the softap config.
1783      */
1784     @Test
testGetWifiApConfigurationNotReturnedWithoutPermission()1785     public void testGetWifiApConfigurationNotReturnedWithoutPermission() throws Exception {
1786         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false);
1787         try {
1788             mWifiServiceImpl.getWifiApConfiguration();
1789             fail("Expected a SecurityException");
1790         } catch (SecurityException e) {
1791         }
1792     }
1793 
1794     /**
1795      * Ensure permitted callers are able to retrieve the softap config.
1796      */
1797     @Test
testGetWifiApConfigurationSuccess()1798     public void testGetWifiApConfigurationSuccess() throws Exception {
1799         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1800         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(true);
1801         SoftApConfiguration apConfig = new SoftApConfiguration.Builder().build();
1802         when(mWifiApConfigStore.getApConfiguration()).thenReturn(apConfig);
1803 
1804         mLooper.startAutoDispatch();
1805         WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp(
1806                 apConfig.toWifiConfiguration(),
1807                 mWifiServiceImpl.getWifiApConfiguration());
1808 
1809         mLooper.stopAutoDispatchAndIgnoreExceptions();
1810     }
1811 
1812     /**
1813      * Ensure we return the proper variable for the softap state after getting an AP state change
1814      * broadcast.
1815      */
1816     @Test
testGetWifiApEnabled()1817     public void testGetWifiApEnabled() throws Exception {
1818         // ap should be disabled when wifi hasn't been started
1819         assertEquals(WifiManager.WIFI_AP_STATE_DISABLED, mWifiServiceImpl.getWifiApEnabledState());
1820 
1821         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1822         mWifiServiceImpl.checkAndStartWifi();
1823         mLooper.dispatchAll();
1824 
1825         // ap should be disabled initially
1826         assertEquals(WifiManager.WIFI_AP_STATE_DISABLED, mWifiServiceImpl.getWifiApEnabledState());
1827 
1828         // send an ap state change to verify WifiServiceImpl is updated
1829         verifyApRegistration();
1830         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
1831         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_FAILED, SAP_START_FAILURE_GENERAL);
1832         mLooper.dispatchAll();
1833 
1834         assertEquals(WifiManager.WIFI_AP_STATE_FAILED, mWifiServiceImpl.getWifiApEnabledState());
1835     }
1836 
1837     /**
1838      * Ensure we do not allow unpermitted callers to get the wifi ap state.
1839      */
1840     @Test
testGetWifiApEnabledPermissionDenied()1841     public void testGetWifiApEnabledPermissionDenied() {
1842         // we should not be able to get the state
1843         doThrow(new SecurityException()).when(mContext)
1844                 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE),
1845                                                 eq("WifiService"));
1846 
1847         try {
1848             mWifiServiceImpl.getWifiApEnabledState();
1849             fail("expected SecurityException");
1850         } catch (SecurityException expected) { }
1851     }
1852 
1853     /**
1854      * Make sure we do start WifiController (wifi disabled) if the device is already decrypted.
1855      */
1856     @Test
testWifiControllerStartsWhenDeviceBootsWithWifiDisabled()1857     public void testWifiControllerStartsWhenDeviceBootsWithWifiDisabled() {
1858         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1859         mWifiServiceImpl.checkAndStartWifi();
1860         mLooper.dispatchAll();
1861         verify(mWifiConfigManager).loadFromStore();
1862         verify(mActiveModeWarden).start();
1863         verify(mActiveModeWarden, never()).wifiToggled(any());
1864     }
1865 
1866     @Test
testWifiVerboseLoggingInitialization()1867     public void testWifiVerboseLoggingInitialization() {
1868         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
1869         when(mWifiSettingsConfigStore.get(eq(WIFI_VERBOSE_LOGGING_ENABLED))).thenReturn(true);
1870         mWifiServiceImpl.checkAndStartWifi();
1871         mLooper.dispatchAll();
1872         verify(mWifiConfigManager).loadFromStore();
1873         verify(mActiveModeWarden).enableVerboseLogging(true);
1874         // show key mode is always disabled at the beginning.
1875         verify(mWifiGlobals).setShowKeyVerboseLoggingModeEnabled(eq(false));
1876         verify(mActiveModeWarden).start();
1877     }
1878 
1879     /**
1880      * Make sure we do start WifiController (wifi enabled) if the device is already decrypted.
1881      */
1882     @Test
testWifiFullyStartsWhenDeviceBootsWithWifiEnabled()1883     public void testWifiFullyStartsWhenDeviceBootsWithWifiEnabled() {
1884         when(mSettingsStore.handleWifiToggled(true)).thenReturn(true);
1885         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(true);
1886         when(mActiveModeWarden.getWifiState()).thenReturn(WIFI_STATE_DISABLED);
1887         when(mContext.getPackageName()).thenReturn(ANDROID_SYSTEM_PACKAGE);
1888         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
1889                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
1890         mWifiServiceImpl.checkAndStartWifi();
1891         mLooper.dispatchAll();
1892         verify(mWifiMetrics).start();
1893         verify(mWifiConfigManager).loadFromStore();
1894         verify(mActiveModeWarden).start();
1895     }
1896 
1897     @Test
testSetPulledAtomCallbacks()1898     public void testSetPulledAtomCallbacks() {
1899         mWifiServiceImpl.checkAndStartWifi();
1900         mLooper.dispatchAll();
1901         verify(mWifiPulledAtomLogger).setPullAtomCallback(WifiStatsLog.WIFI_MODULE_INFO);
1902     }
1903 
1904     /**
1905      * Verify that the setCoexUnsafeChannels calls the corresponding CoexManager API if
1906      * the config_wifiDefaultCoexAlgorithmEnabled is false.
1907      */
1908     @Test
testSetCoexUnsafeChannelsDefaultAlgorithmDisabled()1909     public void testSetCoexUnsafeChannelsDefaultAlgorithmDisabled() {
1910         assumeTrue(SdkLevel.isAtLeastS());
1911         when(mResources.getBoolean(R.bool.config_wifiDefaultCoexAlgorithmEnabled))
1912                 .thenReturn(false);
1913         List<CoexUnsafeChannel> unsafeChannels = new ArrayList<>();
1914         unsafeChannels.addAll(Arrays.asList(new CoexUnsafeChannel(WIFI_BAND_24_GHZ, 6),
1915                 new CoexUnsafeChannel(WIFI_BAND_5_GHZ, 36)));
1916         int coexRestrictions = COEX_RESTRICTION_SOFTAP
1917                 & COEX_RESTRICTION_WIFI_AWARE & COEX_RESTRICTION_WIFI_DIRECT;
1918         mWifiServiceImpl.setCoexUnsafeChannels(unsafeChannels, coexRestrictions);
1919         mLooper.dispatchAll();
1920         verify(mCoexManager, times(1)).setCoexUnsafeChannels(any(), anyInt());
1921     }
1922 
1923     /**
1924      * Verify that the setCoexUnsafeChannels does not call the corresponding CoexManager API if
1925      * the config_wifiDefaultCoexAlgorithmEnabled is true.
1926      */
1927     @Test
testSetCoexUnsafeChannelsDefaultAlgorithmEnabled()1928     public void testSetCoexUnsafeChannelsDefaultAlgorithmEnabled() {
1929         assumeTrue(SdkLevel.isAtLeastS());
1930         when(mResources.getBoolean(R.bool.config_wifiDefaultCoexAlgorithmEnabled))
1931                 .thenReturn(true);
1932         List<CoexUnsafeChannel> unsafeChannels = new ArrayList<>();
1933         unsafeChannels.add(new CoexUnsafeChannel(WIFI_BAND_24_GHZ, 6));
1934         unsafeChannels.add(new CoexUnsafeChannel(WIFI_BAND_5_GHZ, 36));
1935         int coexRestrictions = COEX_RESTRICTION_SOFTAP
1936                 & COEX_RESTRICTION_WIFI_AWARE & COEX_RESTRICTION_WIFI_DIRECT;
1937         mWifiServiceImpl.setCoexUnsafeChannels(unsafeChannels, coexRestrictions);
1938         mLooper.dispatchAll();
1939         verify(mCoexManager, never()).setCoexUnsafeChannels(any(), anyInt());
1940     }
1941 
1942     /**
1943      * Verify that setCoexUnsafeChannels throws an IllegalArgumentException if passed a null set.
1944      */
1945     @Test
testSetCoexUnsafeChannelsNullSet()1946     public void testSetCoexUnsafeChannelsNullSet() {
1947         assumeTrue(SdkLevel.isAtLeastS());
1948         try {
1949             mWifiServiceImpl.setCoexUnsafeChannels(null, 0);
1950             fail("Expected IllegalArgumentException");
1951         } catch (IllegalArgumentException e) {
1952         }
1953     }
1954 
1955     /**
1956      * Test register and unregister callback will go to CoexManager;
1957      */
1958     @Test
testRegisterUnregisterCoexCallback()1959     public void testRegisterUnregisterCoexCallback() throws Exception {
1960         assumeTrue(SdkLevel.isAtLeastS());
1961         when(mCoexCallback.asBinder()).thenReturn(mAppBinder);
1962         mWifiServiceImpl.registerCoexCallback(mCoexCallback);
1963         mLooper.dispatchAll();
1964         verify(mCoexManager).registerRemoteCoexCallback(mCoexCallback);
1965         mWifiServiceImpl.unregisterCoexCallback(mCoexCallback);
1966         mLooper.dispatchAll();
1967         verify(mCoexManager).unregisterRemoteCoexCallback(mCoexCallback);
1968     }
1969 
1970     /**
1971      * Verify that a call to setCoexUnsafeChannels throws a SecurityException if the caller does
1972      * not have the WIFI_UPDATE_COEX_UNSAFE_CHANNELS permission.
1973      */
1974     @Test
testSetCoexUnsafeChannelsThrowsSecurityExceptionOnMissingPermissions()1975     public void testSetCoexUnsafeChannelsThrowsSecurityExceptionOnMissingPermissions() {
1976         assumeTrue(SdkLevel.isAtLeastS());
1977         doThrow(new SecurityException()).when(mContext)
1978                 .enforceCallingOrSelfPermission(eq(WIFI_UPDATE_COEX_UNSAFE_CHANNELS),
1979                         eq("WifiService"));
1980         try {
1981             mWifiServiceImpl.setCoexUnsafeChannels(new ArrayList<>(), 0);
1982             fail("expected SecurityException");
1983         } catch (SecurityException expected) { }
1984     }
1985 
1986     /**
1987      * Verify that a call to registerCoexCallback throws a SecurityException if the caller does
1988      * not have the WIFI_ACCESS_COEX_UNSAFE_CHANNELS permission.
1989      */
1990     @Test
testRegisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions()1991     public void testRegisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions() {
1992         assumeTrue(SdkLevel.isAtLeastS());
1993         doThrow(new SecurityException()).when(mContext)
1994                 .enforceCallingOrSelfPermission(eq(WIFI_ACCESS_COEX_UNSAFE_CHANNELS),
1995                         eq("WifiService"));
1996         try {
1997             mWifiServiceImpl.registerCoexCallback(mCoexCallback);
1998             fail("expected SecurityException");
1999         } catch (SecurityException expected) { }
2000     }
2001 
2002     /**
2003      * Verify that a call to unregisterCoexCallback throws a SecurityException if the caller does
2004      * not have the WIFI_ACCESS_COEX_UNSAFE_CHANNELS permission.
2005      */
2006     @Test
testUnregisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions()2007     public void testUnregisterCoexCallbackThrowsSecurityExceptionOnMissingPermissions() {
2008         assumeTrue(SdkLevel.isAtLeastS());
2009         doThrow(new SecurityException()).when(mContext)
2010                 .enforceCallingOrSelfPermission(eq(WIFI_ACCESS_COEX_UNSAFE_CHANNELS),
2011                         eq("WifiService"));
2012         try {
2013             mWifiServiceImpl.unregisterCoexCallback(mCoexCallback);
2014             fail("expected SecurityException");
2015         } catch (SecurityException expected) { }
2016     }
2017 
2018     /**
2019      * Verify caller with proper permission can call startSoftAp.
2020      */
2021     @Test
testStartSoftApWithPermissionsAndNullConfig()2022     public void testStartSoftApWithPermissionsAndNullConfig() {
2023         mLooper.startAutoDispatch();
2024         boolean result = mWifiServiceImpl.startSoftAp(null, TEST_PACKAGE_NAME);
2025         mLooper.stopAutoDispatchAndIgnoreExceptions();
2026         assertTrue(result);
2027         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2028                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2029         assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2030     }
2031 
2032     /**
2033      * Verify caller with proper permissions but an invalid config does not start softap.
2034      */
2035     @Test
testStartSoftApWithPermissionsAndInvalidConfig()2036     public void testStartSoftApWithPermissionsAndInvalidConfig() {
2037         mLooper.startAutoDispatch();
2038         boolean result = mWifiServiceImpl.startSoftAp(mApConfig, TEST_PACKAGE_NAME);
2039         mLooper.stopAutoDispatchAndIgnoreExceptions();
2040         assertFalse(result);
2041         verify(mActiveModeWarden, never()).startSoftAp(any(),
2042                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2043     }
2044 
2045     /**
2046      * Verify caller with proper permission and valid config does start softap.
2047      */
2048     @Test
testStartSoftApWithPermissionsAndValidConfig()2049     public void testStartSoftApWithPermissionsAndValidConfig() {
2050         WifiConfiguration config = createValidWifiApConfiguration();
2051         mLooper.startAutoDispatch();
2052         boolean result = mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME);
2053         mLooper.stopAutoDispatchAndIgnoreExceptions();
2054         assertTrue(result);
2055         verify(mActiveModeWarden).startSoftAp(
2056                 mSoftApModeConfigCaptor.capture(),
2057                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2058         WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp(
2059                 config,
2060                 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration());
2061         verify(mLastCallerInfoManager).put(eq(WifiManager.API_SOFT_AP), anyInt(),
2062                 anyInt(), anyInt(), anyString(), eq(true));
2063     }
2064 
2065     /**
2066      * Verify a SecurityException is thrown when a caller without the correct permission attempts to
2067      * start softap.
2068      */
2069     @Test(expected = SecurityException.class)
testStartSoftApWithoutPermissionThrowsException()2070     public void testStartSoftApWithoutPermissionThrowsException() throws Exception {
2071         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK))
2072                 .thenReturn(PackageManager.PERMISSION_DENIED);
2073         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
2074                 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any());
2075         mLooper.startAutoDispatch();
2076         mWifiServiceImpl.startSoftAp(null, TEST_PACKAGE_NAME);
2077         mLooper.stopAutoDispatchAndIgnoreExceptions();
2078     }
2079 
2080     /**
2081      * Verify that startSoftAP() succeeds if the caller does not have the NETWORK_STACK permission
2082      * but does have the MAINLINE_NETWORK_STACK permission.
2083      */
2084     @Test
testStartSoftApWithoutNetworkStackWithMainlineNetworkStackSucceeds()2085     public void testStartSoftApWithoutNetworkStackWithMainlineNetworkStackSucceeds() {
2086         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK))
2087                 .thenReturn(PackageManager.PERMISSION_DENIED);
2088         WifiConfiguration config = createValidWifiApConfiguration();
2089         mLooper.startAutoDispatch();
2090         boolean result = mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME);
2091         mLooper.stopAutoDispatchAndIgnoreExceptions();
2092         assertTrue(result);
2093         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2094                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2095         WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp(
2096                 config,
2097                 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration());
2098         verify(mContext).enforceCallingOrSelfPermission(
2099                 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any());
2100     }
2101 
2102     /**
2103      * Verify that startSoftAp() with valid config succeeds after a failed call
2104      */
2105     @Test
testStartSoftApWithValidConfigSucceedsAfterFailure()2106     public void testStartSoftApWithValidConfigSucceedsAfterFailure() {
2107         // First initiate a failed call
2108         mLooper.startAutoDispatch();
2109         assertFalse(mWifiServiceImpl.startSoftAp(mApConfig, TEST_PACKAGE_NAME));
2110         mLooper.stopAutoDispatchAndIgnoreExceptions();
2111         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2112 
2113         // Next attempt a valid config
2114         WifiConfiguration config = createValidWifiApConfiguration();
2115         mLooper.startAutoDispatch();
2116         assertTrue(mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME));
2117         mLooper.stopAutoDispatchAndIgnoreExceptions();
2118         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2119                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2120         WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp(
2121                 config,
2122                 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration());
2123     }
2124 
2125     /**
2126      * Verify caller with proper permission can call startTetheredHotspot.
2127      */
2128     @Test
testStartTetheredHotspotWithPermissionsAndNullConfig()2129     public void testStartTetheredHotspotWithPermissionsAndNullConfig() {
2130         mLooper.startAutoDispatch();
2131         boolean result = mWifiServiceImpl.startTetheredHotspot(null, TEST_PACKAGE_NAME);
2132         mLooper.stopAutoDispatchAndIgnoreExceptions();
2133         assertTrue(result);
2134         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2135                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2136         assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2137         verify(mLastCallerInfoManager).put(eq(WifiManager.API_TETHERED_HOTSPOT), anyInt(),
2138                 anyInt(), anyInt(), anyString(), eq(true));
2139     }
2140 
2141     /**
2142      * Verify caller with proper permissions but an invalid config does not start softap.
2143      */
2144     @Test
testStartTetheredHotspotWithPermissionsAndInvalidConfig()2145     public void testStartTetheredHotspotWithPermissionsAndInvalidConfig() {
2146         mLooper.startAutoDispatch();
2147         boolean result = mWifiServiceImpl.startTetheredHotspot(
2148                 new SoftApConfiguration.Builder().build(), TEST_PACKAGE_NAME);
2149         mLooper.stopAutoDispatchAndIgnoreExceptions();
2150         assertFalse(result);
2151         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2152     }
2153 
2154     /**
2155      * Verify caller with proper permission and valid config does start softap.
2156      */
2157     @Test
testStartTetheredHotspotWithPermissionsAndValidConfig()2158     public void testStartTetheredHotspotWithPermissionsAndValidConfig() {
2159         SoftApConfiguration config = createValidSoftApConfiguration();
2160         mLooper.startAutoDispatch();
2161         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2162         mLooper.stopAutoDispatchAndIgnoreExceptions();
2163         assertTrue(result);
2164         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2165                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2166         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2167     }
2168 
2169     /**
2170      * Verify that while the DISALLOW_WIFI_TETHERING user restriction is set, softap does not start.
2171      */
2172     @Test
testStartTetheredHotspotWithUserRestriction()2173     public void testStartTetheredHotspotWithUserRestriction() {
2174         assumeTrue(SdkLevel.isAtLeastT());
2175         when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_TETHERING)).thenReturn(true);
2176         mWifiServiceImpl.checkAndStartWifi();
2177         mLooper.dispatchAll();
2178         SoftApConfiguration config = createValidSoftApConfiguration();
2179         mLooper.startAutoDispatch();
2180         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2181         mLooper.stopAutoDispatchAndIgnoreExceptions();
2182         assertFalse(result);
2183         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2184     }
2185 
2186     /**
2187      * Verify that when the DISALLOW_WIFI_TETHERING user restriction is set, softap stops.
2188      */
2189     @Test
testTetheredHotspotDisabledWhenUserRestrictionSet()2190     public void testTetheredHotspotDisabledWhenUserRestrictionSet() {
2191         assumeTrue(SdkLevel.isAtLeastT());
2192         when(mBundle.getBoolean(UserManager.DISALLOW_WIFI_TETHERING)).thenReturn(true);
2193         mLooper.startAutoDispatch();
2194         mWifiServiceImpl.onUserRestrictionsChanged();
2195         mLooper.stopAutoDispatchAndIgnoreExceptions();
2196         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_TETHERED);
2197     }
2198 
2199     /**
2200      * Verify isWifiBandSupported for 24GHz with an overlay override config
2201      */
2202     @Test
testIsWifiBandSupported24gWithOverride()2203     public void testIsWifiBandSupported24gWithOverride() throws Exception {
2204         when(mResources.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(true);
2205         assertTrue(mWifiServiceImpl.is24GHzBandSupported());
2206         verify(mActiveModeWarden, never()).isBandSupportedForSta(anyInt());
2207     }
2208 
2209     /**
2210      * Verify isWifiBandSupported for 5GHz with an overlay override config
2211      */
2212     @Test
testIsWifiBandSupported5gWithOverride()2213     public void testIsWifiBandSupported5gWithOverride() throws Exception {
2214         when(mResources.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(true);
2215         assertTrue(mWifiServiceImpl.is5GHzBandSupported());
2216         verify(mActiveModeWarden, never()).isBandSupportedForSta(anyInt());
2217     }
2218 
2219     /**
2220      * Verify isWifiBandSupported for 6GHz with an overlay override config
2221      */
2222     @Test
testIsWifiBandSupported6gWithOverride()2223     public void testIsWifiBandSupported6gWithOverride() throws Exception {
2224         when(mResources.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(true);
2225         assertTrue(mWifiServiceImpl.is6GHzBandSupported());
2226         verify(mActiveModeWarden, never()).isBandSupportedForSta(anyInt());
2227     }
2228 
2229     /**
2230      * Verify isWifiBandSupported for 24GHz with no overlay override config no channels
2231      */
2232     @Test
testIsWifiBandSupported24gNoOverrideNoChannels()2233     public void testIsWifiBandSupported24gNoOverrideNoChannels() throws Exception {
2234         when(mResources.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(false);
2235         when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_24_GHZ)).thenReturn(false);
2236         assertFalse(mWifiServiceImpl.is24GHzBandSupported());
2237         verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_24_GHZ);
2238     }
2239 
2240     /**
2241      * Verify isWifiBandSupported for 5GHz with no overlay override config no channels
2242      */
2243     @Test
testIsWifiBandSupported5gNoOverrideNoChannels()2244     public void testIsWifiBandSupported5gNoOverrideNoChannels() throws Exception {
2245         when(mResources.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(false);
2246         when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_5_GHZ)).thenReturn(false);
2247         assertFalse(mWifiServiceImpl.is5GHzBandSupported());
2248         verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_5_GHZ);
2249     }
2250 
2251     /**
2252      * Verify isWifiBandSupported for 24GHz with no overlay override config with channels
2253      */
2254     @Test
testIsWifiBandSupported24gNoOverrideWithChannels()2255     public void testIsWifiBandSupported24gNoOverrideWithChannels() throws Exception {
2256         when(mResources.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(false);
2257         when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_24_GHZ)).thenReturn(true);
2258         assertTrue(mWifiServiceImpl.is24GHzBandSupported());
2259         verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_24_GHZ);
2260     }
2261 
2262     /**
2263      * Verify isWifiBandSupported for 5GHz with no overlay override config with channels
2264      */
2265     @Test
testIsWifiBandSupported5gNoOverrideWithChannels()2266     public void testIsWifiBandSupported5gNoOverrideWithChannels() throws Exception {
2267         when(mResources.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(false);
2268         when(mActiveModeWarden.isBandSupportedForSta(WIFI_BAND_5_GHZ)).thenReturn(true);
2269         assertTrue(mWifiServiceImpl.is5GHzBandSupported());
2270         verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_5_GHZ);
2271     }
2272 
2273     /**
2274      * Verify isWifiBandSupported for 6GHz with no overlay override config no channels
2275      */
2276     @Test
testIsWifiBandSupported6gNoOverrideNoChannels()2277     public void testIsWifiBandSupported6gNoOverrideNoChannels() throws Exception {
2278         when(mResources.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(false);
2279         when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ)).thenReturn(
2280                 false);
2281         assertFalse(mWifiServiceImpl.is6GHzBandSupported());
2282         verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ);
2283     }
2284 
2285     /**
2286      * Verify isWifiBandSupported for 6GHz with no overlay override config with channels
2287      */
2288     @Test
testIsWifiBandSupported6gNoOverrideWithChannels()2289     public void testIsWifiBandSupported6gNoOverrideWithChannels() throws Exception {
2290         when(mResources.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(false);
2291         when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ)).thenReturn(
2292                 true);
2293         assertTrue(mWifiServiceImpl.is6GHzBandSupported());
2294         verify(mActiveModeWarden).isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ);
2295     }
2296 
setup24GhzSupported()2297     private void setup24GhzSupported() {
2298         when(mResources.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(true);
2299         when(mResources.getBoolean(R.bool.config_wifiSoftap24ghzSupported)).thenReturn(true);
2300     }
2301 
setup24GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2302     private void setup24GhzUnsupported(boolean isOnlyUnsupportedSoftAp) {
2303         when(mResources.getBoolean(R.bool.config_wifiSoftap24ghzSupported)).thenReturn(false);
2304         if (!isOnlyUnsupportedSoftAp) {
2305             when(mResources.getBoolean(R.bool.config_wifi24ghzSupport)).thenReturn(false);
2306             when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_24_GHZ))
2307                     .thenReturn(false);
2308         }
2309     }
2310 
setup5GhzSupported()2311     private void setup5GhzSupported() {
2312         when(mResources.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(true);
2313         when(mResources.getBoolean(R.bool.config_wifiSoftap5ghzSupported)).thenReturn(true);
2314     }
2315 
setup5GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2316     private void setup5GhzUnsupported(boolean isOnlyUnsupportedSoftAp) {
2317         when(mResources.getBoolean(R.bool.config_wifiSoftap5ghzSupported)).thenReturn(false);
2318         if (!isOnlyUnsupportedSoftAp) {
2319             when(mResources.getBoolean(R.bool.config_wifi5ghzSupport)).thenReturn(false);
2320             when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_5_GHZ))
2321                     .thenReturn(false);
2322         }
2323     }
2324 
setup6GhzSupported()2325     private void setup6GhzSupported() {
2326         when(mResources.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(true);
2327         when(mResources.getBoolean(R.bool.config_wifiSoftap6ghzSupported)).thenReturn(true);
2328     }
2329 
setup6GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2330     private void setup6GhzUnsupported(boolean isOnlyUnsupportedSoftAp) {
2331         when(mResources.getBoolean(R.bool.config_wifiSoftap6ghzSupported)).thenReturn(false);
2332         if (!isOnlyUnsupportedSoftAp) {
2333             when(mResources.getBoolean(R.bool.config_wifi6ghzSupport)).thenReturn(false);
2334             when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_6_GHZ))
2335                     .thenReturn(false);
2336         }
2337     }
2338 
setup60GhzSupported()2339     private void setup60GhzSupported() {
2340         when(mResources.getBoolean(R.bool.config_wifi60ghzSupport)).thenReturn(true);
2341         when(mResources.getBoolean(R.bool.config_wifiSoftap60ghzSupported)).thenReturn(true);
2342     }
2343 
setup60GhzUnsupported(boolean isOnlyUnsupportedSoftAp)2344     private void setup60GhzUnsupported(boolean isOnlyUnsupportedSoftAp) {
2345         when(mResources.getBoolean(R.bool.config_wifiSoftap60ghzSupported)).thenReturn(false);
2346         if (!isOnlyUnsupportedSoftAp) {
2347             when(mResources.getBoolean(R.bool.config_wifi60ghzSupport)).thenReturn(false);
2348             when(mActiveModeWarden.isBandSupportedForSta(WifiScanner.WIFI_BAND_60_GHZ))
2349                     .thenReturn(false);
2350         }
2351     }
2352 
2353     /**
2354      * Verify attempt to start softAp with a supported 24GHz band succeeds.
2355      */
2356     @Test
testStartTetheredHotspotWithSupported24gBand()2357     public void testStartTetheredHotspotWithSupported24gBand() {
2358         setup24GhzSupported();
2359 
2360         SoftApConfiguration config = new SoftApConfiguration.Builder()
2361                 .setSsid("TestAp")
2362                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2363                 .setBand(SoftApConfiguration.BAND_2GHZ)
2364                 .build();
2365 
2366         mLooper.startAutoDispatch();
2367         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2368         mLooper.stopAutoDispatchAndIgnoreExceptions();
2369 
2370         assertTrue(result);
2371         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2372                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2373         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2374     }
2375 
2376     /**
2377      * Verify attempt to start softAp with a non-supported 2.4GHz band fails.
2378      */
2379     @Test
testStartTetheredHotspotWithUnSupported24gBand()2380     public void testStartTetheredHotspotWithUnSupported24gBand() {
2381         setup24GhzUnsupported(false);
2382 
2383         SoftApConfiguration config = new SoftApConfiguration.Builder()
2384                 .setSsid("TestAp")
2385                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2386                 .setBand(SoftApConfiguration.BAND_2GHZ)
2387                 .build();
2388 
2389         mLooper.startAutoDispatch();
2390         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2391         mLooper.stopAutoDispatchAndIgnoreExceptions();
2392 
2393         assertFalse(result);
2394         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2395     }
2396 
2397     /**
2398      * Verify attempt to start softAp with a non-supported 2.4GHz band fails.
2399      */
2400     @Test
testStartTetheredHotspotWithUnSupportedSoftAp24gBand()2401     public void testStartTetheredHotspotWithUnSupportedSoftAp24gBand() {
2402         setup24GhzSupported();
2403         setup24GhzUnsupported(true);
2404 
2405         SoftApConfiguration config = new SoftApConfiguration.Builder()
2406                 .setSsid("TestAp")
2407                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2408                 .setBand(SoftApConfiguration.BAND_2GHZ)
2409                 .build();
2410 
2411         mLooper.startAutoDispatch();
2412         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2413         mLooper.stopAutoDispatchAndIgnoreExceptions();
2414 
2415         assertFalse(result);
2416         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2417     }
2418 
2419     /**
2420      * Verify attempt to start softAp with a supported 5GHz band succeeds.
2421      */
2422     @Test
testStartTetheredHotspotWithSupported5gBand()2423     public void testStartTetheredHotspotWithSupported5gBand() {
2424         setup5GhzSupported();
2425 
2426         SoftApConfiguration config = new SoftApConfiguration.Builder()
2427                 .setSsid("TestAp")
2428                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2429                 .setBand(SoftApConfiguration.BAND_5GHZ)
2430                 .build();
2431 
2432         mLooper.startAutoDispatch();
2433         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2434         mLooper.stopAutoDispatchAndIgnoreExceptions();
2435 
2436         assertTrue(result);
2437         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2438                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2439         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2440     }
2441 
2442     /**
2443      * Verify attempt to start softAp with a non-supported 5GHz band fails.
2444      */
2445     @Test
testStartTetheredHotspotWithUnSupported5gBand()2446     public void testStartTetheredHotspotWithUnSupported5gBand() {
2447         setup5GhzUnsupported(false);
2448 
2449         SoftApConfiguration config = new SoftApConfiguration.Builder()
2450                 .setSsid("TestAp")
2451                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2452                 .setBand(SoftApConfiguration.BAND_5GHZ)
2453                 .build();
2454 
2455         mLooper.startAutoDispatch();
2456         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2457         mLooper.stopAutoDispatchAndIgnoreExceptions();
2458 
2459         assertFalse(result);
2460         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2461     }
2462 
2463     /**
2464      * Verify attempt to start softAp with a non-supported 5GHz band fails.
2465      */
2466     @Test
testStartTetheredHotspotWithUnSupportedSoftAp5gBand()2467     public void testStartTetheredHotspotWithUnSupportedSoftAp5gBand() {
2468         setup5GhzSupported();
2469         setup5GhzUnsupported(true);
2470 
2471         SoftApConfiguration config = new SoftApConfiguration.Builder()
2472                 .setSsid("TestAp")
2473                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2474                 .setBand(SoftApConfiguration.BAND_5GHZ)
2475                 .build();
2476 
2477         mLooper.startAutoDispatch();
2478         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2479         mLooper.stopAutoDispatchAndIgnoreExceptions();
2480 
2481         assertFalse(result);
2482         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2483     }
2484 
2485     /**
2486      * Verify attempt to start softAp with a supported 6GHz band succeeds.
2487      */
2488     @Test
testStartTetheredHotspotWithSupported6gBand()2489     public void testStartTetheredHotspotWithSupported6gBand() {
2490         setup6GhzSupported();
2491 
2492         SoftApConfiguration config = new SoftApConfiguration.Builder()
2493                 .setSsid("TestAp")
2494                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE)
2495                 .setBand(SoftApConfiguration.BAND_6GHZ)
2496                 .build();
2497 
2498         mLooper.startAutoDispatch();
2499         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2500         mLooper.stopAutoDispatchAndIgnoreExceptions();
2501 
2502         assertTrue(result);
2503         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2504                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2505         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2506     }
2507 
2508     /**
2509      * Verify attempt to start softAp with a non-supported 6GHz band fails.
2510      */
2511     @Test
testStartTetheredHotspotWithUnSupported6gBand()2512     public void testStartTetheredHotspotWithUnSupported6gBand() {
2513         setup6GhzUnsupported(false);
2514 
2515         SoftApConfiguration config = new SoftApConfiguration.Builder()
2516                 .setSsid("TestAp")
2517                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE)
2518                 .setBand(SoftApConfiguration.BAND_6GHZ)
2519                 .build();
2520 
2521         mLooper.startAutoDispatch();
2522         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2523         mLooper.stopAutoDispatchAndIgnoreExceptions();
2524 
2525         assertFalse(result);
2526         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2527     }
2528 
2529     /**
2530      * Verify attempt to start softAp with a non-supported 6GHz band fails.
2531      */
2532     @Test
testStartTetheredHotspotWithUnSupportedSoftAp6gBand()2533     public void testStartTetheredHotspotWithUnSupportedSoftAp6gBand() {
2534         setup6GhzSupported();
2535         setup6GhzUnsupported(true);
2536 
2537         SoftApConfiguration config = new SoftApConfiguration.Builder()
2538                 .setSsid("TestAp")
2539                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE)
2540                 .setBand(SoftApConfiguration.BAND_6GHZ)
2541                 .build();
2542 
2543         mLooper.startAutoDispatch();
2544         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2545         mLooper.stopAutoDispatchAndIgnoreExceptions();
2546 
2547         assertFalse(result);
2548         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2549     }
2550 
2551 
2552     /**
2553      * Verify attempt to start softAp with a supported 60GHz band succeeds.
2554      */
2555     @Test
testStartTetheredHotspotWithSupported60gBand()2556     public void testStartTetheredHotspotWithSupported60gBand() {
2557         setup60GhzSupported();
2558 
2559         SoftApConfiguration config = new SoftApConfiguration.Builder()
2560                 .setSsid("TestAp")
2561                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2562                 .setBand(SoftApConfiguration.BAND_60GHZ)
2563                 .build();
2564 
2565         mLooper.startAutoDispatch();
2566         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2567         mLooper.stopAutoDispatchAndIgnoreExceptions();
2568 
2569         assertTrue(result);
2570         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2571                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2572         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2573     }
2574 
2575     /**
2576      * Verify attempt to start softAp with a non-supported 60GHz band fails.
2577      */
2578     @Test
testStartTetheredHotspotWithUnSupported60gBand()2579     public void testStartTetheredHotspotWithUnSupported60gBand() {
2580         setup60GhzUnsupported(false);
2581 
2582         SoftApConfiguration config = new SoftApConfiguration.Builder()
2583                 .setSsid("TestAp")
2584                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2585                 .setBand(SoftApConfiguration.BAND_60GHZ)
2586                 .build();
2587 
2588         mLooper.startAutoDispatch();
2589         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2590         mLooper.stopAutoDispatchAndIgnoreExceptions();
2591 
2592         assertFalse(result);
2593         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2594     }
2595 
2596     /**
2597      * Verify attempt to start softAp with a non-supported 60GHz band fails.
2598      */
2599     @Test
testStartTetheredHotspotWithUnSupportedSoftAp60gBand()2600     public void testStartTetheredHotspotWithUnSupportedSoftAp60gBand() {
2601         setup60GhzSupported();
2602         setup60GhzUnsupported(true);
2603 
2604         SoftApConfiguration config = new SoftApConfiguration.Builder()
2605                 .setSsid("TestAp")
2606                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2607                 .setBand(SoftApConfiguration.BAND_60GHZ)
2608                 .build();
2609 
2610         mLooper.startAutoDispatch();
2611         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2612         mLooper.stopAutoDispatchAndIgnoreExceptions();
2613 
2614         assertFalse(result);
2615         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2616     }
2617 
2618     /**
2619      * Verify attempt to start softAp with a supported band succeeds.
2620      */
2621     @Test
testStartTetheredHotspotWithSupportedBand()2622     public void testStartTetheredHotspotWithSupportedBand() {
2623         setup5GhzSupported();
2624 
2625         SoftApConfiguration config = new SoftApConfiguration.Builder()
2626                 .setSsid("TestAp")
2627                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
2628                 .setBand(SoftApConfiguration.BAND_5GHZ)
2629                 .build();
2630 
2631         mLooper.startAutoDispatch();
2632         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2633         mLooper.stopAutoDispatchAndIgnoreExceptions();
2634 
2635         assertTrue(result);
2636         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2637                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2638         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2639     }
2640 
2641     /**
2642      * Verify a SecurityException is thrown when a caller without the correct permission attempts to
2643      * start softap.
2644      */
2645     @Test(expected = SecurityException.class)
testStartTetheredHotspotWithoutPermissionThrowsException()2646     public void testStartTetheredHotspotWithoutPermissionThrowsException() throws Exception {
2647         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK))
2648                 .thenReturn(PackageManager.PERMISSION_DENIED);
2649         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
2650                 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any());
2651         mWifiServiceImpl.startTetheredHotspot(null, TEST_PACKAGE_NAME);
2652     }
2653 
2654     /**
2655      * Verify that startTetheredHotspot() succeeds if the caller does not have the
2656      * NETWORK_STACK permission but does have the MAINLINE_NETWORK_STACK permission.
2657      */
2658     @Test
testStartTetheredHotspotWithoutNetworkStackWithMainlineNetworkStackSucceeds()2659     public void testStartTetheredHotspotWithoutNetworkStackWithMainlineNetworkStackSucceeds() {
2660         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK))
2661                 .thenReturn(PackageManager.PERMISSION_DENIED);
2662         SoftApConfiguration config = createValidSoftApConfiguration();
2663         mLooper.startAutoDispatch();
2664         boolean result = mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME);
2665         assertTrue(result);
2666         mLooper.stopAutoDispatchAndIgnoreExceptions();
2667         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2668                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2669         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2670         verify(mContext).enforceCallingOrSelfPermission(
2671                 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any());
2672     }
2673 
2674     /**
2675      * Verify a valied call to startTetheredHotspot succeeds after a failed call.
2676      */
2677     @Test
testStartTetheredHotspotWithValidConfigSucceedsAfterFailedCall()2678     public void testStartTetheredHotspotWithValidConfigSucceedsAfterFailedCall() {
2679         // First issue an invalid call
2680         mLooper.startAutoDispatch();
2681         assertFalse(mWifiServiceImpl.startTetheredHotspot(
2682                 new SoftApConfiguration.Builder().build(), TEST_PACKAGE_NAME));
2683         mLooper.stopAutoDispatchAndIgnoreExceptions();
2684         verify(mActiveModeWarden, never()).startSoftAp(any(), any());
2685 
2686         // Now attempt a successful call
2687         mLooper.startAutoDispatch();
2688         assertTrue(mWifiServiceImpl.startTetheredHotspot(null, TEST_PACKAGE_NAME));
2689         mLooper.stopAutoDispatchAndIgnoreExceptions();
2690         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
2691                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
2692         assertNull(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
2693     }
2694 
2695     /**
2696      * Verify caller with proper permission can call stopSoftAp.
2697      */
2698     @Test
testStopSoftApWithPermissions()2699     public void testStopSoftApWithPermissions() {
2700         boolean result = mWifiServiceImpl.stopSoftAp();
2701         assertTrue(result);
2702         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_TETHERED);
2703         verify(mLastCallerInfoManager).put(eq(WifiManager.API_SOFT_AP), anyInt(),
2704                 anyInt(), anyInt(), anyString(), eq(false));
2705     }
2706 
2707     /**
2708      * Verify SecurityException is thrown when a caller without the correct permission attempts to
2709      * stop softap.
2710      */
2711     @Test(expected = SecurityException.class)
testStopSoftApWithoutPermissionThrowsException()2712     public void testStopSoftApWithoutPermissionThrowsException() throws Exception {
2713         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK))
2714                 .thenReturn(PackageManager.PERMISSION_DENIED);
2715         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
2716                 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any());
2717         mWifiServiceImpl.stopSoftAp();
2718     }
2719 
2720     /**
2721      * Ensure that we handle app ops check failure when handling scan request.
2722      */
2723     @Test
testStartScanFailureAppOpsIgnored()2724     public void testStartScanFailureAppOpsIgnored() {
2725         doReturn(AppOpsManager.MODE_IGNORED).when(mAppOpsManager)
2726                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), SCAN_PACKAGE_NAME);
2727         mLooper.startAutoDispatch();
2728         assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID));
2729         mLooper.stopAutoDispatchAndIgnoreExceptions();
2730         verify(mScanRequestProxy, never()).startScan(Process.myUid(), SCAN_PACKAGE_NAME);
2731     }
2732 
2733     /**
2734      * Ensure that we handle scan access permission check failure when handling scan request.
2735      */
2736     @Test
testStartScanFailureInCanAccessScanResultsPermission()2737     public void testStartScanFailureInCanAccessScanResultsPermission() {
2738         doThrow(new SecurityException()).when(mWifiPermissionsUtil)
2739                 .enforceCanAccessScanResults(SCAN_PACKAGE_NAME, TEST_FEATURE_ID, Process.myUid(),
2740                         null);
2741         mLooper.startAutoDispatch();
2742         assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID));
2743         mLooper.stopAutoDispatchAndIgnoreExceptions();
2744         verify(mScanRequestProxy, never()).startScan(Process.myUid(), SCAN_PACKAGE_NAME);
2745     }
2746 
2747     /**
2748      * Ensure that we handle scan request failure when posting the runnable to handler fails.
2749      */
2750     @Test
testStartScanFailureInRunWithScissors()2751     public void testStartScanFailureInRunWithScissors() {
2752         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
2753 
2754         mLooper.startAutoDispatch();
2755         assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID));
2756         mLooper.stopAutoDispatchAndIgnoreExceptions();
2757         verify(mScanRequestProxy, never()).startScan(anyInt(), eq(SCAN_PACKAGE_NAME));
2758         verify(mLastCallerInfoManager).put(eq(WifiManager.API_START_SCAN), anyInt(),
2759                 anyInt(), anyInt(), anyString(), eq(true));
2760     }
2761 
2762     /**
2763      * Ensure that we handle scan request failure from ScanRequestProxy fails.
2764      */
2765     @Test
testStartScanFailureFromScanRequestProxy()2766     public void testStartScanFailureFromScanRequestProxy() {
2767         when(mScanRequestProxy.startScan(anyInt(), anyString())).thenReturn(false);
2768 
2769         mLooper.startAutoDispatch();
2770         assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID));
2771         mLooper.stopAutoDispatchAndIgnoreExceptions();
2772         verify(mScanRequestProxy).startScan(Binder.getCallingUid(), SCAN_PACKAGE_NAME);
2773     }
2774 
setupForGetConnectionInfo()2775     private WifiInfo setupForGetConnectionInfo() {
2776         WifiInfo wifiInfo = new WifiInfo();
2777         wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID));
2778         wifiInfo.setBSSID(TEST_BSSID);
2779         wifiInfo.setNetworkId(TEST_NETWORK_ID);
2780         wifiInfo.setFQDN(TEST_FQDN);
2781         wifiInfo.setProviderFriendlyName(TEST_FRIENDLY_NAME);
2782         return wifiInfo;
2783     }
2784 
parcelingRoundTrip(WifiInfo wifiInfo)2785     private WifiInfo parcelingRoundTrip(WifiInfo wifiInfo) {
2786         Parcel parcel = Parcel.obtain();
2787         wifiInfo.writeToParcel(parcel, 0);
2788         // Rewind the pointer to the head of the parcel.
2789         parcel.setDataPosition(0);
2790         return WifiInfo.CREATOR.createFromParcel(parcel);
2791     }
2792 
2793     /**
2794      * Test that connected SSID and BSSID are not exposed to an app that does not have the
2795      * appropriate permissions.
2796      */
2797     @Test
testConnectedIdsAreHiddenFromAppWithoutPermission()2798     public void testConnectedIdsAreHiddenFromAppWithoutPermission() throws Exception {
2799         WifiInfo wifiInfo = setupForGetConnectionInfo();
2800         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
2801 
2802         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults(
2803                 anyString(), nullable(String.class), anyInt(), nullable(String.class));
2804 
2805         mLooper.startAutoDispatch();
2806         WifiInfo connectionInfo = parcelingRoundTrip(
2807                 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID));
2808         mLooper.stopAutoDispatchAndIgnoreExceptions();
2809 
2810         assertEquals(WifiManager.UNKNOWN_SSID, connectionInfo.getSSID());
2811         assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getBSSID());
2812         assertEquals(WifiConfiguration.INVALID_NETWORK_ID, connectionInfo.getNetworkId());
2813         assertNull(connectionInfo.getPasspointFqdn());
2814         assertNull(connectionInfo.getPasspointProviderFriendlyName());
2815         if (SdkLevel.isAtLeastS()) {
2816             try {
2817                 connectionInfo.isPrimary();
2818                 fail();
2819             } catch (SecurityException e) { /* pass */ }
2820         }
2821     }
2822 
2823     /**
2824      * Test that connected SSID and BSSID are not exposed to an app that does not have the
2825      * appropriate permissions, when enforceCanAccessScanResults raises a SecurityException.
2826      */
2827     @Test
testConnectedIdsAreHiddenOnSecurityException()2828     public void testConnectedIdsAreHiddenOnSecurityException() throws Exception {
2829         WifiInfo wifiInfo = setupForGetConnectionInfo();
2830         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
2831 
2832         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults(
2833                 anyString(), nullable(String.class), anyInt(), nullable(String.class));
2834 
2835         mLooper.startAutoDispatch();
2836         WifiInfo connectionInfo = parcelingRoundTrip(
2837                 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID));
2838         mLooper.stopAutoDispatchAndIgnoreExceptions();
2839 
2840         assertEquals(WifiManager.UNKNOWN_SSID, connectionInfo.getSSID());
2841         assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, connectionInfo.getBSSID());
2842         assertEquals(WifiConfiguration.INVALID_NETWORK_ID, connectionInfo.getNetworkId());
2843         assertNull(connectionInfo.getPasspointFqdn());
2844         assertNull(connectionInfo.getPasspointProviderFriendlyName());
2845     }
2846 
2847     /**
2848      * Test that connected SSID and BSSID are exposed to an app that does have the
2849      * appropriate permissions.
2850      */
2851     @Test
testConnectedIdsAreVisibleFromPermittedApp()2852     public void testConnectedIdsAreVisibleFromPermittedApp() throws Exception {
2853         WifiInfo wifiInfo = setupForGetConnectionInfo();
2854         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
2855 
2856         mLooper.startAutoDispatch();
2857         WifiInfo connectionInfo = parcelingRoundTrip(
2858                 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID));
2859         mLooper.stopAutoDispatchAndIgnoreExceptions();
2860 
2861         assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID());
2862         assertEquals(TEST_BSSID, connectionInfo.getBSSID());
2863         assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId());
2864         assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn());
2865         assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName());
2866     }
2867 
2868     /**
2869      * Test that connected SSID and BSSID for secondary CMM are exposed to an app that requests
2870      * the second STA on a device that supports STA + STA.
2871      */
2872     @Test
testConnectedIdsFromSecondaryCmmAreVisibleFromAppRequestingSecondaryCmm()2873     public void testConnectedIdsFromSecondaryCmmAreVisibleFromAppRequestingSecondaryCmm()
2874             throws Exception {
2875         WifiInfo wifiInfo = setupForGetConnectionInfo();
2876         ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class);
2877         when(secondaryCmm.getRequestorWs())
2878                 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE));
2879         when(secondaryCmm.getConnectionInfo()).thenReturn(wifiInfo);
2880         when(mActiveModeWarden.getClientModeManagersInRoles(
2881                 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED))
2882                 .thenReturn(Arrays.asList(secondaryCmm));
2883 
2884         mLooper.startAutoDispatch();
2885         WifiInfo connectionInfo = parcelingRoundTrip(
2886                 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID));
2887         mLooper.stopAutoDispatchAndIgnoreExceptions();
2888 
2889         assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID());
2890         assertEquals(TEST_BSSID, connectionInfo.getBSSID());
2891         assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId());
2892         assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn());
2893         assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName());
2894     }
2895 
2896     /**
2897      * Test that connected SSID and BSSID for secondary CMM are exposed to an app that requests
2898      * the second STA on a device that supports STA + STA. The request WorkSource of CMM is settings
2899      * promoted.
2900      */
2901     @Test
testConnectedIdsAreVisibleFromAppRequestingSecondaryCmmWIthPromotesSettingsWs()2902     public void testConnectedIdsAreVisibleFromAppRequestingSecondaryCmmWIthPromotesSettingsWs()
2903             throws Exception {
2904         WifiInfo wifiInfo = setupForGetConnectionInfo();
2905         ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class);
2906         WorkSource ws = new WorkSource(Binder.getCallingUid(), TEST_PACKAGE);
2907         ws.add(SETTINGS_WORKSOURCE);
2908         when(secondaryCmm.getRequestorWs()).thenReturn(ws);
2909         when(secondaryCmm.getConnectionInfo()).thenReturn(wifiInfo);
2910         when(mActiveModeWarden.getClientModeManagersInRoles(
2911                 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED))
2912                 .thenReturn(Arrays.asList(secondaryCmm));
2913         ConcreteClientModeManager primaryCmm = mock(ConcreteClientModeManager.class);
2914         when(primaryCmm.getConnectionInfo()).thenReturn(new WifiInfo());
2915         when(mActiveModeWarden.getPrimaryClientModeManager()).thenReturn(primaryCmm);
2916         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(SETTINGS_WORKSOURCE.getUid(0)))
2917                 .thenReturn(true);
2918 
2919         mLooper.startAutoDispatch();
2920         WifiInfo connectionInfo = parcelingRoundTrip(
2921                 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID));
2922         mLooper.stopAutoDispatchAndIgnoreExceptions();
2923 
2924         assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID());
2925         assertEquals(TEST_BSSID, connectionInfo.getBSSID());
2926         assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId());
2927         assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn());
2928         assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName());
2929         verify(mActiveModeWarden, never()).getPrimaryClientModeManager();
2930 
2931         mLooper.startAutoDispatch();
2932         connectionInfo = parcelingRoundTrip(mWifiServiceImpl
2933                 .getConnectionInfo(SETTINGS_WORKSOURCE.getPackageName(0), TEST_FEATURE_ID));
2934         mLooper.stopAutoDispatchAndIgnoreExceptions();
2935 
2936         assertEquals(WifiManager.UNKNOWN_SSID, connectionInfo.getSSID());
2937         verify(mActiveModeWarden).getPrimaryClientModeManager();
2938         verify(primaryCmm).getConnectionInfo();
2939     }
2940 
2941     /**
2942      * Test that connected SSID and BSSID for primary CMM are exposed to an app that is not the one
2943      * that requests the second STA on a device that supports STA + STA.
2944      */
2945     @Test
testConnectedIdsFromPrimaryCmmAreVisibleFromAppNotRequestingSecondaryCmm()2946     public void testConnectedIdsFromPrimaryCmmAreVisibleFromAppNotRequestingSecondaryCmm()
2947             throws Exception {
2948         WifiInfo wifiInfo = setupForGetConnectionInfo();
2949         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
2950         ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class);
2951         when(secondaryCmm.getRequestorWs())
2952                 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME_OTHER));
2953         when(mActiveModeWarden.getClientModeManagersInRoles(
2954                 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED))
2955                 .thenReturn(Arrays.asList(secondaryCmm));
2956 
2957         mLooper.startAutoDispatch();
2958         WifiInfo connectionInfo = parcelingRoundTrip(
2959                 mWifiServiceImpl.getConnectionInfo(TEST_PACKAGE, TEST_FEATURE_ID));
2960         mLooper.stopAutoDispatchAndIgnoreExceptions();
2961 
2962         assertEquals(TEST_SSID_WITH_QUOTES, connectionInfo.getSSID());
2963         assertEquals(TEST_BSSID, connectionInfo.getBSSID());
2964         assertEquals(TEST_NETWORK_ID, connectionInfo.getNetworkId());
2965         assertEquals(TEST_FQDN, connectionInfo.getPasspointFqdn());
2966         assertEquals(TEST_FRIENDLY_NAME, connectionInfo.getPasspointProviderFriendlyName());
2967     }
2968 
2969     /**
2970      * Test that configured network list are exposed empty list to an app that does not have the
2971      * appropriate permissions.
2972      */
2973     @Test
testConfiguredNetworkListAreEmptyFromAppWithoutPermission()2974     public void testConfiguredNetworkListAreEmptyFromAppWithoutPermission() throws Exception {
2975         when(mWifiConfigManager.getSavedNetworks(anyInt()))
2976                 .thenReturn(TEST_WIFI_CONFIGURATION_LIST);
2977 
2978         // no permission = target SDK=Q && not a carrier app
2979         when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(anyString())).thenReturn(
2980                 TelephonyManager.CARRIER_PRIVILEGE_STATUS_NO_ACCESS);
2981 
2982         ParceledListSlice<WifiConfiguration> configs =
2983                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false);
2984 
2985         assertEquals(0, configs.getList().size());
2986     }
2987 
2988     /**
2989      * Test that configured network list are exposed empty list to an app that does not have the
2990      * appropriate permissions, when enforceCanAccessScanResults raises a SecurityException.
2991      */
2992     @Test
testConfiguredNetworkListAreEmptyOnSecurityException()2993     public void testConfiguredNetworkListAreEmptyOnSecurityException() throws Exception {
2994         when(mWifiConfigManager.getSavedNetworks(anyInt()))
2995                 .thenReturn(TEST_WIFI_CONFIGURATION_LIST);
2996 
2997         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults(
2998                 anyString(), nullable(String.class), anyInt(), nullable(String.class));
2999 
3000         ParceledListSlice<WifiConfiguration> configs =
3001                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false);
3002 
3003         assertEquals(0, configs.getList().size());
3004 
3005     }
3006 
3007     /**
3008      * Test that configured network list are exposed to an app that does have the
3009      * appropriate permissions.
3010      */
3011     @Test
testConfiguredNetworkListAreVisibleFromPermittedApp()3012     public void testConfiguredNetworkListAreVisibleFromPermittedApp() throws Exception {
3013         when(mWifiConfigManager.getSavedNetworks(anyInt()))
3014                 .thenReturn(TEST_WIFI_CONFIGURATION_LIST);
3015 
3016         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
3017                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
3018 
3019         mLooper.startAutoDispatch();
3020         ParceledListSlice<WifiConfiguration> configs =
3021                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false);
3022         mLooper.stopAutoDispatchAndIgnoreExceptions();
3023 
3024         verify(mWifiConfigManager).getSavedNetworks(eq(WIFI_UID));
3025         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
3026                 TEST_WIFI_CONFIGURATION_LIST, configs.getList());
3027     }
3028 
3029     @Test(expected = SecurityException.class)
testGetCallerConfiguredNetworks_ThrowExceptionIfNotDoOrPO()3030     public void testGetCallerConfiguredNetworks_ThrowExceptionIfNotDoOrPO() {
3031         when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
3032                 .thenReturn(false);
3033         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
3034                 .thenReturn(false);
3035 
3036         mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, true);
3037     }
3038 
3039     @Test
testGetCallerConfiguredNetworks_ReturnsCallerNetworks()3040     public void testGetCallerConfiguredNetworks_ReturnsCallerNetworks() {
3041         final int callerUid = Binder.getCallingUid();
3042         WifiConfiguration callerNetwork0 = WifiConfigurationTestUtil.generateWifiConfig(
3043                 0, callerUid, "\"red\"", true, true, null, null, SECURITY_NONE);
3044         WifiConfiguration callerNetwork1 = WifiConfigurationTestUtil.generateWifiConfig(
3045                 1, callerUid, "\"red\"", true, true, null, null, SECURITY_NONE);
3046         WifiConfiguration nonCallerNetwork0 = WifiConfigurationTestUtil.generateWifiConfig(
3047                 2, 1200000, "\"blue\"", false, true, null, null, SECURITY_NONE);
3048         WifiConfiguration nonCallerNetwork1 = WifiConfigurationTestUtil.generateWifiConfig(
3049                 3, 1100000, "\"cyan\"", true, true, null, null, SECURITY_NONE);
3050         when(mWifiConfigManager.getSavedNetworks(anyInt())).thenReturn(Arrays.asList(
3051                 callerNetwork0, callerNetwork1, nonCallerNetwork0, nonCallerNetwork1));
3052 
3053         // Caller does NOT need to have location permission to be able to retrieve its own networks.
3054         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults(
3055                 anyString(), nullable(String.class), anyInt(), nullable(String.class));
3056         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
3057                 .thenReturn(true);
3058         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
3059                 .thenReturn(true);
3060 
3061         mLooper.startAutoDispatch();
3062         ParceledListSlice<WifiConfiguration> configs =
3063                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, true);
3064         mLooper.stopAutoDispatchAndIgnoreExceptions();
3065 
3066         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
3067                 Arrays.asList(callerNetwork0, callerNetwork1), configs.getList());
3068     }
3069 
3070     /**
3071      * Test that admin may retrieve all networks but mac address is set to default for networks
3072      * they do not own.
3073      */
3074     @Test
testGetConfiguredNetworksAdmin_ReturnsNetworksWithDefaultMac()3075     public void testGetConfiguredNetworksAdmin_ReturnsNetworksWithDefaultMac() {
3076         final int callerUid = Binder.getCallingUid();
3077         WifiConfiguration callerNetwork = WifiConfigurationTestUtil.generateWifiConfig(
3078                 0, callerUid, "\"red\"", true, true, null, null, SECURITY_NONE);
3079         WifiConfiguration nonCallerNetwork = WifiConfigurationTestUtil.generateWifiConfig(
3080                 2, 1200000, "\"blue\"", true, true, null, null, SECURITY_NONE);
3081         callerNetwork.setRandomizedMacAddress(TEST_FACTORY_MAC_ADDR);
3082 
3083         when(mWifiConfigManager.getSavedNetworks(callerUid)).thenReturn(Arrays.asList(
3084                 callerNetwork, nonCallerNetwork));
3085 
3086         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
3087                 .thenReturn(true);
3088         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
3089                 .thenReturn(true);
3090 
3091         mLooper.startAutoDispatch();
3092         ParceledListSlice<WifiConfiguration> configs =
3093                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID, false);
3094         mLooper.stopAutoDispatchAndIgnoreExceptions();
3095 
3096         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
3097                 Arrays.asList(callerNetwork, nonCallerNetwork), configs.getList());
3098 
3099         for (WifiConfiguration config : configs.getList()) {
3100             if (config.getProfileKey().equals(callerNetwork.getProfileKey())) {
3101                 assertEquals(TEST_FACTORY_MAC, config.getRandomizedMacAddress().toString());
3102             } else {
3103                 assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS,
3104                         config.getRandomizedMacAddress().toString());
3105             }
3106         }
3107     }
3108 
3109     /**
3110      * Test that privileged network list are exposed null to an app that targets T or later and does
3111      * not have nearby devices permission.
3112      */
3113     @Test
testPrivilegedConfiguredNetworkListNullOnSecurityExceptionPostT()3114     public void testPrivilegedConfiguredNetworkListNullOnSecurityExceptionPostT() {
3115         assumeTrue(SdkLevel.isAtLeastT());
3116         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
3117                 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false);
3118         when(mWifiConfigManager.getConfiguredNetworksWithPasswords())
3119                 .thenReturn(TEST_WIFI_CONFIGURATION_LIST);
3120 
3121         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
3122                 any(), anyBoolean(), any());
3123 
3124         mLooper.startAutoDispatch();
3125         ParceledListSlice<WifiConfiguration> configs =
3126                 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID,
3127                         mExtras);
3128         mLooper.stopAutoDispatchAndIgnoreExceptions();
3129 
3130         assertNull(configs);
3131     }
3132 
3133     /**
3134      * Test that privileged network list are exposed null to an app that does not have the
3135      * appropriate permissions, when enforceCanAccessScanResults raises a SecurityException.
3136      */
3137     @Test
testPrivilegedConfiguredNetworkListAreEmptyOnSecurityException()3138     public void testPrivilegedConfiguredNetworkListAreEmptyOnSecurityException() {
3139         when(mWifiConfigManager.getConfiguredNetworksWithPasswords())
3140                 .thenReturn(TEST_WIFI_CONFIGURATION_LIST);
3141 
3142         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceCanAccessScanResults(
3143                 anyString(), nullable(String.class), anyInt(), nullable(String.class));
3144 
3145         mLooper.startAutoDispatch();
3146         ParceledListSlice<WifiConfiguration> configs =
3147                 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID,
3148                         mExtras);
3149         mLooper.stopAutoDispatchAndIgnoreExceptions();
3150 
3151         assertNull(configs);
3152     }
3153 
3154     /**
3155      * Test that privileged network list are exposed to an app that does have the
3156      * appropriate permissions (simulated by not throwing an exception for READ_WIFI_CREDENTIAL).
3157      */
3158     @Test
testPrivilegedConfiguredNetworkListAreVisibleFromPermittedApp()3159     public void testPrivilegedConfiguredNetworkListAreVisibleFromPermittedApp() {
3160         when(mWifiConfigManager.getConfiguredNetworksWithPasswords())
3161                 .thenReturn(TEST_WIFI_CONFIGURATION_LIST);
3162 
3163         mLooper.startAutoDispatch();
3164         ParceledListSlice<WifiConfiguration> configs =
3165                 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID,
3166                         mExtras);
3167         mLooper.stopAutoDispatchAndIgnoreExceptions();
3168 
3169         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
3170                 TEST_WIFI_CONFIGURATION_LIST, configs.getList());
3171     }
3172 
3173     /**
3174      * Test fetching of scan results.
3175      */
3176     @Test
testGetScanResults()3177     public void testGetScanResults() {
3178         ScanResult[] scanResults =
3179                 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0]
3180                         .getResults();
3181         List<ScanResult> scanResultList =
3182                 new ArrayList<>(Arrays.asList(scanResults));
3183         when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList);
3184 
3185         String packageName = "test.com";
3186         String featureId = "test.com.featureId";
3187         mLooper.startAutoDispatch();
3188         List<ScanResult> retrievedScanResultList = mWifiServiceImpl.getScanResults(packageName,
3189                 featureId);
3190         mLooper.stopAutoDispatchAndIgnoreExceptions();
3191         verify(mScanRequestProxy).getScanResults();
3192 
3193         ScanTestUtil.assertScanResultsEquals(scanResults,
3194                 retrievedScanResultList.toArray(new ScanResult[retrievedScanResultList.size()]));
3195     }
3196 
3197     /**
3198      * Ensure that we handle scan results failure when posting the runnable to handler fails.
3199      */
3200     @Test
testGetScanResultsFailureInRunWithScissors()3201     public void testGetScanResultsFailureInRunWithScissors() {
3202         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
3203 
3204         ScanResult[] scanResults =
3205                 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0]
3206                         .getResults();
3207         List<ScanResult> scanResultList =
3208                 new ArrayList<>(Arrays.asList(scanResults));
3209         when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList);
3210 
3211         String packageName = "test.com";
3212         String featureId = "test.com.featureId";
3213         mLooper.startAutoDispatch();
3214         List<ScanResult> retrievedScanResultList = mWifiServiceImpl.getScanResults(packageName,
3215                 featureId);
3216         mLooper.stopAutoDispatchAndIgnoreExceptions();
3217         verify(mScanRequestProxy, never()).getScanResults();
3218 
3219         assertTrue(retrievedScanResultList.isEmpty());
3220     }
3221 
3222     /**
3223      * Test fetching of matching scan results with provided WifiNetworkSuggestion, but it doesn't
3224      * specify the scan results to be filtered.
3225      */
3226     @Test
testGetMatchingScanResultsWithoutSpecifiedScanResults()3227     public void testGetMatchingScanResultsWithoutSpecifiedScanResults() {
3228         ScanResult[] scanResults =
3229                 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0]
3230                         .getResults();
3231         List<ScanResult> scanResultList =
3232                 new ArrayList<>(Arrays.asList(scanResults));
3233         when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList);
3234         WifiNetworkSuggestion mockSuggestion = mock(WifiNetworkSuggestion.class);
3235         List<WifiNetworkSuggestion> matchingSuggestions = List.of(mockSuggestion);
3236         Map<WifiNetworkSuggestion, List<ScanResult>> result = Map.of(
3237                 mockSuggestion, scanResultList);
3238         when(mWifiNetworkSuggestionsManager.getMatchingScanResults(eq(matchingSuggestions),
3239                 eq(scanResultList))).thenReturn(result);
3240 
3241         String packageName = "test.com";
3242         String featureId = "test.com.featureId";
3243         mLooper.startAutoDispatch();
3244         Map<WifiNetworkSuggestion, List<ScanResult>> retrievedScanResults =
3245                 mWifiServiceImpl.getMatchingScanResults(
3246                         matchingSuggestions, null, packageName, featureId);
3247         mLooper.stopAutoDispatchAndIgnoreExceptions();
3248 
3249         ScanTestUtil.assertScanResultsEquals(scanResults,
3250                 retrievedScanResults.get(mockSuggestion)
3251                         .toArray(new ScanResult[retrievedScanResults.size()]));
3252     }
3253 
3254     /**
3255      * Test fetching of matching scan results with provided WifiNetworkSuggestion and ScanResults.
3256      */
3257     @Test
testGetMatchingScanResultsWithSpecifiedScanResults()3258     public void testGetMatchingScanResultsWithSpecifiedScanResults() {
3259         ScanResult[] scanResults =
3260                 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0]
3261                         .getResults();
3262         List<ScanResult> scanResultList =
3263                 new ArrayList<>(Arrays.asList(scanResults));
3264         WifiNetworkSuggestion mockSuggestion = mock(WifiNetworkSuggestion.class);
3265         List<WifiNetworkSuggestion> matchingSuggestions = List.of(mockSuggestion);
3266         Map<WifiNetworkSuggestion, List<ScanResult>> result = Map.of(
3267                 mockSuggestion, scanResultList);
3268 
3269         when(mWifiNetworkSuggestionsManager.getMatchingScanResults(eq(matchingSuggestions),
3270                 eq(scanResultList))).thenReturn(result);
3271 
3272         String packageName = "test.com";
3273         String featureId = "test.com.featureId";
3274         mLooper.startAutoDispatch();
3275         Map<WifiNetworkSuggestion, List<ScanResult>> retrievedScanResults =
3276                 mWifiServiceImpl.getMatchingScanResults(
3277                         matchingSuggestions, scanResultList, packageName, featureId);
3278         mLooper.stopAutoDispatchAndIgnoreExceptions();
3279 
3280         ScanTestUtil.assertScanResultsEquals(scanResults,
3281                 retrievedScanResults.get(mockSuggestion)
3282                         .toArray(new ScanResult[retrievedScanResults.size()]));
3283     }
3284 
3285     /**
3286      * Ensure that we handle failure when posting the runnable to handler fails.
3287      */
3288     @Test
testGetMatchingScanResultsFailureInRunWithScissors()3289     public void testGetMatchingScanResultsFailureInRunWithScissors() {
3290         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
3291 
3292         ScanResult[] scanResults =
3293                 ScanTestUtil.createScanDatas(new int[][]{{2417, 2427, 5180, 5170}})[0]
3294                         .getResults();
3295         List<ScanResult> scanResultList =
3296                 new ArrayList<>(Arrays.asList(scanResults));
3297         when(mScanRequestProxy.getScanResults()).thenReturn(scanResultList);
3298         WifiNetworkSuggestion mockSuggestion = mock(WifiNetworkSuggestion.class);
3299         List<WifiNetworkSuggestion> matchingSuggestions = List.of(mockSuggestion);
3300         Map<WifiNetworkSuggestion, List<ScanResult>> result = Map.of(
3301                 mockSuggestion, scanResultList);
3302 
3303         when(mWifiNetworkSuggestionsManager.getMatchingScanResults(eq(matchingSuggestions),
3304                 eq(scanResultList))).thenReturn(result);
3305 
3306         String packageName = "test.com";
3307         String featureId = "test.com.featureId";
3308         mLooper.startAutoDispatch();
3309         Map<WifiNetworkSuggestion, List<ScanResult>> retrievedScanResults =
3310                 mWifiServiceImpl.getMatchingScanResults(
3311                         matchingSuggestions, null, packageName, featureId);
3312         mLooper.stopAutoDispatchAndIgnoreExceptions();
3313 
3314         assertTrue(retrievedScanResults.isEmpty());
3315     }
3316 
setupLohsPermissions()3317     private void setupLohsPermissions() {
3318         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
3319         when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(true);
3320         when(mUserManager.hasUserRestrictionForUser(
3321                 eq(UserManager.DISALLOW_CONFIG_TETHERING), any()))
3322                 .thenReturn(false);
3323     }
3324 
registerLOHSRequestFull()3325     private void registerLOHSRequestFull() {
3326         setupLohsPermissions();
3327         int result = mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME,
3328                 TEST_FEATURE_ID, null, mExtras);
3329         assertEquals(LocalOnlyHotspotCallback.REQUEST_REGISTERED, result);
3330         verifyCheckChangePermission(TEST_PACKAGE_NAME);
3331     }
3332 
3333     /**
3334      * Verify that the call to startLocalOnlyHotspot returns REQUEST_REGISTERED when successfully
3335      * called.
3336      */
3337     @Test
testStartLocalOnlyHotspotSingleRegistrationReturnsRequestRegistered()3338     public void testStartLocalOnlyHotspotSingleRegistrationReturnsRequestRegistered() {
3339         mLooper.startAutoDispatch();
3340         registerLOHSRequestFull();
3341         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3342         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), any());
3343     }
3344 
3345     /**
3346      * Verify that a call to startLocalOnlyHotspot throws a SecurityException if the caller does not
3347      * have the CHANGE_WIFI_STATE permission.
3348      */
3349     @Test(expected = SecurityException.class)
testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutCorrectPermission()3350     public void testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutCorrectPermission() {
3351         doThrow(new SecurityException()).when(mContext)
3352                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.CHANGE_WIFI_STATE),
3353                                                 eq("WifiService"));
3354         mWifiServiceImpl.startLocalOnlyHotspot(
3355                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3356     }
3357 
3358     /**
3359      * Verify that a call to startLocalOnlyHotspot throws a SecurityException if the caller does not
3360      * have Location permission.
3361      */
3362     @Test(expected = SecurityException.class)
testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationPermission()3363     public void testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationPermission() {
3364         doThrow(new SecurityException())
3365                 .when(mWifiPermissionsUtil).enforceLocationPermission(eq(TEST_PACKAGE_NAME),
3366                                                                       eq(TEST_FEATURE_ID),
3367                                                                       anyInt());
3368         mWifiServiceImpl.startLocalOnlyHotspot(
3369                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3370     }
3371 
3372     /**
3373      * Verify that a call to startLocalOnlyHotspot throws a SecurityException if the caller targets
3374      * Android T or later and does not have nearby devices permission.
3375      */
3376     @Test(expected = SecurityException.class)
testStartLocalOnlyHotspotThrowsExceptionWithoutNearbyDevicesPermissionOnT()3377     public void testStartLocalOnlyHotspotThrowsExceptionWithoutNearbyDevicesPermissionOnT() {
3378         assumeTrue(SdkLevel.isAtLeastT());
3379         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
3380                 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false);
3381         doThrow(new SecurityException())
3382                 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
3383                         any(), anyBoolean(), any());
3384         mWifiServiceImpl.startLocalOnlyHotspot(
3385                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3386     }
3387 
3388     /**
3389      * Verify that a call to startLocalOnlyHotspot will not check nearby devices permission if the
3390      * caller does not target T.
3391      */
3392     @Test
testStartLocalOnlyHotspotDoesNotCheckNearbyPermissionIfTargetPreT()3393     public void testStartLocalOnlyHotspotDoesNotCheckNearbyPermissionIfTargetPreT() {
3394         assumeTrue(SdkLevel.isAtLeastT());
3395         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
3396         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
3397                 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(true);
3398         mWifiServiceImpl.startLocalOnlyHotspot(
3399                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3400         verify(mWifiPermissionsUtil, never()).enforceNearbyDevicesPermission(any(), anyBoolean(),
3401                 any());
3402     }
3403 
3404     /**
3405      * Verify that a call to startLocalOnlyHotspot throws a SecurityException if Location mode is
3406      * disabled.
3407      */
3408     @Test(expected = SecurityException.class)
testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationEnabled()3409     public void testStartLocalOnlyHotspotThrowsSecurityExceptionWithoutLocationEnabled() {
3410         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false);
3411         mWifiServiceImpl.startLocalOnlyHotspot(
3412                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3413     }
3414 
3415     /**
3416      * Only start LocalOnlyHotspot if the caller is the foreground app at the time of the request.
3417      */
3418     @Test
testStartLocalOnlyHotspotFailsIfRequestorNotForegroundApp()3419     public void testStartLocalOnlyHotspotFailsIfRequestorNotForegroundApp() throws Exception {
3420         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
3421 
3422         when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(false);
3423         int result = mWifiServiceImpl.startLocalOnlyHotspot(
3424                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3425         assertEquals(LocalOnlyHotspotCallback.ERROR_INCOMPATIBLE_MODE, result);
3426     }
3427 
3428     /**
3429      * Only start tethering if we are not tethering.
3430      */
3431     @Test
testTetheringDoesNotStartWhenAlreadyTetheringActive()3432     public void testTetheringDoesNotStartWhenAlreadyTetheringActive() throws Exception {
3433         WifiConfiguration config = createValidWifiApConfiguration();
3434         mLooper.startAutoDispatch();
3435         assertTrue(mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME));
3436         mLooper.stopAutoDispatchAndIgnoreExceptions();
3437         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
3438                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
3439         WifiConfigurationTestUtil.assertConfigurationEqualForSoftAp(
3440                 config,
3441                 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration().toWifiConfiguration());
3442         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
3443         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
3444         mLooper.dispatchAll();
3445         assertEquals(WIFI_AP_STATE_ENABLED, mWifiServiceImpl.getWifiApEnabledState());
3446         reset(mActiveModeWarden);
3447 
3448         // Start another session without a stop, that should fail.
3449         mLooper.startAutoDispatch();
3450         assertFalse(mWifiServiceImpl.startSoftAp(
3451                 createValidWifiApConfiguration(), TEST_PACKAGE_NAME));
3452         mLooper.stopAutoDispatchAndIgnoreExceptions();
3453 
3454         verifyNoMoreInteractions(mActiveModeWarden);
3455     }
3456 
3457     /**
3458      * Only start tethering if we are not tethering in new API: startTetheredHotspot.
3459      */
3460     @Test
testStartTetheredHotspotDoesNotStartWhenAlreadyTetheringActive()3461     public void testStartTetheredHotspotDoesNotStartWhenAlreadyTetheringActive() throws Exception {
3462         SoftApConfiguration config = createValidSoftApConfiguration();
3463         mLooper.startAutoDispatch();
3464         assertTrue(mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME));
3465         mLooper.stopAutoDispatch();
3466         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(),
3467                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
3468         assertThat(config).isEqualTo(mSoftApModeConfigCaptor.getValue().getSoftApConfiguration());
3469         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
3470         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
3471         mLooper.dispatchAll();
3472         assertEquals(WIFI_AP_STATE_ENABLED, mWifiServiceImpl.getWifiApEnabledState());
3473         reset(mActiveModeWarden);
3474 
3475         // Start another session without a stop, that should fail.
3476         mLooper.startAutoDispatch();
3477         assertFalse(mWifiServiceImpl.startTetheredHotspot(config, TEST_PACKAGE_NAME));
3478         mLooper.stopAutoDispatchAndIgnoreExceptions();
3479 
3480         verifyNoMoreInteractions(mActiveModeWarden);
3481     }
3482 
3483     /**
3484      * Only start LocalOnlyHotspot if we are not tethering.
3485      */
3486     @Test
testHotspotDoesNotStartWhenAlreadyTethering()3487     public void testHotspotDoesNotStartWhenAlreadyTethering() throws Exception {
3488         WifiConfiguration config = createValidWifiApConfiguration();
3489         mLooper.startAutoDispatch();
3490         assertTrue(mWifiServiceImpl.startSoftAp(config, TEST_PACKAGE_NAME));
3491         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
3492         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
3493         mLooper.stopAutoDispatchAndIgnoreExceptions();
3494 
3495         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
3496         when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(true);
3497         mLooper.dispatchAll();
3498         int returnCode = mWifiServiceImpl.startLocalOnlyHotspot(
3499                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3500         assertEquals(ERROR_INCOMPATIBLE_MODE, returnCode);
3501     }
3502 
3503     /**
3504      * Only start LocalOnlyHotspot if admin setting does not disallow tethering.
3505      */
3506     @Test
testHotspotDoesNotStartWhenTetheringDisallowed()3507     public void testHotspotDoesNotStartWhenTetheringDisallowed() throws Exception {
3508         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
3509         when(mFrameworkFacade.isAppForeground(any(), anyInt())).thenReturn(true);
3510         when(mUserManager.hasUserRestrictionForUser(
3511                 eq(UserManager.DISALLOW_CONFIG_TETHERING), any()))
3512                 .thenReturn(true);
3513         int returnCode = mWifiServiceImpl.startLocalOnlyHotspot(
3514                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3515         assertEquals(ERROR_TETHERING_DISALLOWED, returnCode);
3516     }
3517 
3518     /**
3519      * Verify that callers can only have one registered LOHS request.
3520      */
3521     @Test(expected = IllegalStateException.class)
testStartLocalOnlyHotspotThrowsExceptionWhenCallerAlreadyRegistered()3522     public void testStartLocalOnlyHotspotThrowsExceptionWhenCallerAlreadyRegistered() {
3523         mLooper.startAutoDispatch();
3524         registerLOHSRequestFull();
3525         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3526 
3527         // now do the second request that will fail
3528         mWifiServiceImpl.startLocalOnlyHotspot(
3529                 mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
3530     }
3531 
3532     /**
3533      * Verify that the call to stopLocalOnlyHotspot does not do anything when there aren't any
3534      * registered callers.
3535      */
3536     @Test
testStopLocalOnlyHotspotDoesNothingWithoutRegisteredRequests()3537     public void testStopLocalOnlyHotspotDoesNothingWithoutRegisteredRequests() throws Exception {
3538         // allow test to proceed without a permission check failure
3539         mWifiServiceImpl.stopLocalOnlyHotspot();
3540         mLooper.dispatchAll();
3541         // there is nothing registered, so this shouldn't do anything
3542         verify(mActiveModeWarden, never()).stopSoftAp(anyInt());
3543     }
3544 
3545     /**
3546      * Verify that the call to stopLocalOnlyHotspot does not do anything when one caller unregisters
3547      * but there is still an active request
3548      */
3549     @Test
testStopLocalOnlyHotspotDoesNothingWithRemainingRequest()3550     public void testStopLocalOnlyHotspotDoesNothingWithRemainingRequest() throws Exception {
3551         mLooper.startAutoDispatch();
3552         // register a request that will remain after the stopLOHS call
3553         mWifiServiceImpl.registerLOHSForTest(mPid, mRequestInfo);
3554 
3555         setupLocalOnlyHotspot();
3556         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3557         // Since we are calling with the same pid, the second register call will be removed
3558         mWifiServiceImpl.stopLocalOnlyHotspot();
3559         mLooper.dispatchAll();
3560         // there is still a valid registered request - do not tear down LOHS
3561         verify(mActiveModeWarden, never()).stopSoftAp(anyInt());
3562     }
3563 
3564     /**
3565      * Verify that the call to stopLocalOnlyHotspot sends a message to WifiController to stop
3566      * the softAp when there is one registered caller when that caller is removed.
3567      */
3568     @Test
testStopLocalOnlyHotspotTriggersStopWithOneRegisteredRequest()3569     public void testStopLocalOnlyHotspotTriggersStopWithOneRegisteredRequest() throws Exception {
3570         setupLocalOnlyHotspot();
3571 
3572         verify(mActiveModeWarden).startSoftAp(any(), any());
3573 
3574         mWifiServiceImpl.stopLocalOnlyHotspot();
3575         mLooper.dispatchAll();
3576 
3577         // No permission check required for change_wifi_state.
3578         verify(mContext, never()).enforceCallingOrSelfPermission(
3579                 eq("android.Manifest.permission.CHANGE_WIFI_STATE"), anyString());
3580 
3581         // there is was only one request registered, we should tear down LOHS
3582         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY);
3583     }
3584 
3585     /**
3586      * Verify that by default startLocalOnlyHotspot starts access point at 2 GHz.
3587      */
3588     @Test
testStartLocalOnlyHotspotAt2Ghz()3589     public void testStartLocalOnlyHotspotAt2Ghz() {
3590         SoftApConfiguration lohsConfig = createValidSoftApConfiguration();
3591         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
3592                 eq(mContext), eq(null), any())).thenReturn(lohsConfig);
3593         mLooper.startAutoDispatch();
3594         registerLOHSRequestFull();
3595         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3596         verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig(
3597                 eq(mContext), eq(null), any());
3598         verifyLohsBand(SoftApConfiguration.BAND_2GHZ);
3599     }
3600 
verifyLohsBand(int expectedBand)3601     private void verifyLohsBand(int expectedBand) {
3602         verify(mActiveModeWarden).startSoftAp(mSoftApModeConfigCaptor.capture(), any());
3603         final SoftApConfiguration configuration =
3604                 mSoftApModeConfigCaptor.getValue().getSoftApConfiguration();
3605         assertNotNull(configuration);
3606         assertEquals(expectedBand, configuration.getBand());
3607     }
3608 
3609     private static class FakeLohsCallback extends ILocalOnlyHotspotCallback.Stub {
3610         boolean mIsStarted = false;
3611         SoftApConfiguration mSoftApConfig = null;
3612 
3613         @Override
onHotspotStarted(SoftApConfiguration softApConfig)3614         public void onHotspotStarted(SoftApConfiguration softApConfig) {
3615             mIsStarted = true;
3616             this.mSoftApConfig = softApConfig;
3617         }
3618 
3619         @Override
onHotspotStopped()3620         public void onHotspotStopped() {
3621             mIsStarted = false;
3622             mSoftApConfig = null;
3623         }
3624 
3625         @Override
onHotspotFailed(int i)3626         public void onHotspotFailed(int i) {
3627             mIsStarted = false;
3628             mSoftApConfig = null;
3629         }
3630     }
3631 
setupForCustomLohs()3632     private void setupForCustomLohs() {
3633         setupLohsPermissions();
3634         when(mContext.checkPermission(eq(Manifest.permission.NETWORK_SETUP_WIZARD),
3635                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
3636         setupWardenForCustomLohs();
3637     }
3638 
setupWardenForCustomLohs()3639     private void setupWardenForCustomLohs() {
3640         doAnswer(invocation -> {
3641             changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR);
3642             mWifiServiceImpl.updateInterfaceIpState(mLohsInterfaceName, IFACE_IP_MODE_LOCAL_ONLY);
3643             return null;
3644         }).when(mActiveModeWarden).startSoftAp(any(), any());
3645     }
3646 
3647     @Test(expected = SecurityException.class)
testCustomLohs_FailsWithoutPermission()3648     public void testCustomLohs_FailsWithoutPermission() {
3649         SoftApConfiguration customConfig = new SoftApConfiguration.Builder()
3650                 .setSsid("customConfig")
3651                 .build();
3652         // set up basic permissions, but not NETWORK_SETUP_WIZARD
3653         setupLohsPermissions();
3654         setupWardenForCustomLohs();
3655         mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME, TEST_FEATURE_ID,
3656                 customConfig, mExtras);
3657     }
3658 
nopDeathCallback(LocalOnlyHotspotRequestInfo requestor)3659     private static void nopDeathCallback(LocalOnlyHotspotRequestInfo requestor) {
3660     }
3661 
3662     @Test
testCustomLohs_ExclusiveAfterShared()3663     public void testCustomLohs_ExclusiveAfterShared() {
3664         mLooper.startAutoDispatch();
3665         FakeLohsCallback sharedCallback = new FakeLohsCallback();
3666         FakeLohsCallback exclusiveCallback = new FakeLohsCallback();
3667         SoftApConfiguration exclusiveConfig = new SoftApConfiguration.Builder()
3668                 .setSsid("customSsid")
3669                 .build();
3670 
3671         setupForCustomLohs();
3672         mWifiServiceImpl.registerLOHSForTest(mPid,
3673                 new LocalOnlyHotspotRequestInfo(mLooper.getLooper(), new WorkSource(),
3674                         sharedCallback, WifiServiceImplTest::nopDeathCallback, null));
3675         assertThat(mWifiServiceImpl.startLocalOnlyHotspot(exclusiveCallback, TEST_PACKAGE_NAME,
3676                 TEST_FEATURE_ID, exclusiveConfig, mExtras)).isEqualTo(ERROR_GENERIC);
3677         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3678         assertThat(sharedCallback.mIsStarted).isTrue();
3679         assertThat(exclusiveCallback.mIsStarted).isFalse();
3680     }
3681 
3682     @Test
testCustomLohs_ExclusiveBeforeShared()3683     public void testCustomLohs_ExclusiveBeforeShared() {
3684         mLooper.startAutoDispatch();
3685         FakeLohsCallback sharedCallback = new FakeLohsCallback();
3686         FakeLohsCallback exclusiveCallback = new FakeLohsCallback();
3687         SoftApConfiguration exclusiveConfig = new SoftApConfiguration.Builder()
3688                 .setSsid("customSsid")
3689                 .build();
3690 
3691         setupForCustomLohs();
3692         mWifiServiceImpl.registerLOHSForTest(mPid,
3693                 new LocalOnlyHotspotRequestInfo(mLooper.getLooper(), new WorkSource(),
3694                         exclusiveCallback, WifiServiceImplTest::nopDeathCallback, exclusiveConfig));
3695         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3696         assertThat(mWifiServiceImpl.startLocalOnlyHotspot(sharedCallback, TEST_PACKAGE_NAME,
3697                 TEST_FEATURE_ID, null, mExtras)).isEqualTo(ERROR_GENERIC);
3698         assertThat(exclusiveCallback.mIsStarted).isTrue();
3699         assertThat(sharedCallback.mIsStarted).isFalse();
3700     }
3701 
3702     @Test
testCustomLohs_Wpa2()3703     public void testCustomLohs_Wpa2() {
3704         SoftApConfiguration config = new SoftApConfiguration.Builder()
3705                 .setSsid("customSsid")
3706                 .setPassphrase("passphrase", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
3707                 .build();
3708         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
3709                 eq(mContext), eq(config), any())).thenReturn(config);
3710         FakeLohsCallback callback = new FakeLohsCallback();
3711         mLooper.startAutoDispatch();
3712         setupForCustomLohs();
3713         assertThat(
3714                 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID,
3715                         config, mExtras)).isEqualTo(REQUEST_REGISTERED);
3716         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3717         verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig(
3718                 eq(mContext), eq(config), any());
3719         // Use app's worksouce.
3720         verify(mActiveModeWarden).startSoftAp(any(),
3721                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
3722         assertThat(callback.mIsStarted).isTrue();
3723         assertThat(callback.mSoftApConfig.getWifiSsid().getUtf8Text()).isEqualTo("customSsid");
3724         assertThat(callback.mSoftApConfig.getSecurityType())
3725                 .isEqualTo(SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);
3726         assertThat(callback.mSoftApConfig.getPassphrase()).isEqualTo("passphrase");
3727     }
3728 
3729     @Test
testCustomLohs_Open()3730     public void testCustomLohs_Open() {
3731         SoftApConfiguration config = new SoftApConfiguration.Builder()
3732                 .setSsid("customSsid")
3733                 .build();
3734         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
3735                 eq(mContext), eq(config), any())).thenReturn(config);
3736         FakeLohsCallback callback = new FakeLohsCallback();
3737         mLooper.startAutoDispatch();
3738         setupForCustomLohs();
3739         assertThat(
3740                 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID,
3741                         config, mExtras)).isEqualTo(REQUEST_REGISTERED);
3742         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3743         verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig(
3744                 eq(mContext), eq(config), any());
3745         // Use app's worksouce.
3746         verify(mActiveModeWarden).startSoftAp(any(),
3747                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
3748         assertThat(callback.mIsStarted).isTrue();
3749         assertThat(callback.mSoftApConfig.getWifiSsid().getUtf8Text()).isEqualTo("customSsid");
3750         assertThat(callback.mSoftApConfig.getSecurityType())
3751                 .isEqualTo(SoftApConfiguration.SECURITY_TYPE_OPEN);
3752         assertThat(callback.mSoftApConfig.getPassphrase()).isNull();
3753     }
3754 
3755     @Test
testCustomLohs_GeneratesSsidIfAbsent()3756     public void testCustomLohs_GeneratesSsidIfAbsent() {
3757         SoftApConfiguration lohsConfig = createValidSoftApConfiguration();
3758         SoftApConfiguration customizedConfig = new SoftApConfiguration.Builder()
3759                 .setPassphrase("passphrase", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
3760                 .build();
3761         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
3762                 eq(mContext), eq(customizedConfig), any()))
3763                 .thenReturn(lohsConfig);
3764         mLooper.startAutoDispatch();
3765         FakeLohsCallback callback = new FakeLohsCallback();
3766 
3767         setupForCustomLohs();
3768         assertThat(
3769                 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID,
3770                         customizedConfig, mExtras)).isEqualTo(REQUEST_REGISTERED);
3771         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3772         verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig(
3773                 eq(mContext), eq(customizedConfig), any());
3774         // Use app's worksouce.
3775         verify(mActiveModeWarden).startSoftAp(any(),
3776                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
3777         assertThat(callback.mIsStarted).isTrue();
3778         assertThat(callback.mSoftApConfig.getWifiSsid()).isNotNull();
3779     }
3780 
3781     @Test
testCustomLohs_ForwardsBssid()3782     public void testCustomLohs_ForwardsBssid() {
3783         mLooper.startAutoDispatch();
3784         SoftApConfiguration lohsConfig = createValidSoftApConfiguration();
3785         SoftApConfiguration.Builder customizedConfigBuilder =
3786                 new SoftApConfiguration.Builder(lohsConfig)
3787                 .setBssid(MacAddress.fromString("aa:bb:cc:dd:ee:ff"));
3788         if (SdkLevel.isAtLeastS()) {
3789             customizedConfigBuilder.setMacRandomizationSetting(
3790                     SoftApConfiguration.RANDOMIZATION_NONE);
3791         }
3792         SoftApConfiguration customizedConfig = customizedConfigBuilder.build();
3793         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
3794                 eq(mContext), eq(customizedConfig), any()))
3795                 .thenReturn(customizedConfig);
3796         FakeLohsCallback callback = new FakeLohsCallback();
3797 
3798         setupForCustomLohs();
3799         assertThat(
3800                 mWifiServiceImpl.startLocalOnlyHotspot(callback, TEST_PACKAGE_NAME, TEST_FEATURE_ID,
3801                         customizedConfig, mExtras)).isEqualTo(REQUEST_REGISTERED);
3802         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3803 
3804         // Use app's worksouce.
3805         verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig(
3806                 eq(mContext), eq(customizedConfig), any());
3807         verify(mActiveModeWarden).startSoftAp(any(),
3808                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
3809         assertThat(callback.mIsStarted).isTrue();
3810         assertThat(callback.mSoftApConfig.getBssid().toString())
3811                 .ignoringCase().isEqualTo("aa:bb:cc:dd:ee:ff");
3812     }
3813 
3814     /**
3815          * Verify that WifiServiceImpl does not send the stop ap message if there were no
3816          * pending LOHS requests upon a binder death callback.
3817          */
3818     @Test
testServiceImplNotCalledWhenBinderDeathTriggeredNoRequests()3819     public void testServiceImplNotCalledWhenBinderDeathTriggeredNoRequests() {
3820         LocalOnlyRequestorCallback binderDeathCallback =
3821                 mWifiServiceImpl.new LocalOnlyRequestorCallback();
3822 
3823         binderDeathCallback.onLocalOnlyHotspotRequestorDeath(mRequestInfo);
3824         verify(mActiveModeWarden, never()).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY);
3825     }
3826 
3827     /**
3828      * Verify that WifiServiceImpl does not send the stop ap message if there are remaining
3829      * registered LOHS requests upon a binder death callback.  Additionally verify that softap mode
3830      * will be stopped if that remaining request is removed (to verify the binder death properly
3831      * cleared the requestor that died).
3832      */
3833     @Test
testServiceImplNotCalledWhenBinderDeathTriggeredWithRequests()3834     public void testServiceImplNotCalledWhenBinderDeathTriggeredWithRequests() throws Exception {
3835         mLooper.startAutoDispatch();
3836         LocalOnlyRequestorCallback binderDeathCallback =
3837                 mWifiServiceImpl.new LocalOnlyRequestorCallback();
3838 
3839         // registering a request directly from the test will not trigger a message to start
3840         // softap mode
3841         mWifiServiceImpl.registerLOHSForTest(mPid, mRequestInfo);
3842 
3843         setupLocalOnlyHotspot();
3844 
3845         binderDeathCallback.onLocalOnlyHotspotRequestorDeath(mRequestInfo);
3846         verify(mActiveModeWarden, never()).stopSoftAp(anyInt());
3847 
3848         reset(mActiveModeWarden);
3849 
3850         // now stop as the second request and confirm CMD_SET_AP will be sent to make sure binder
3851         // death requestor was removed
3852         mWifiServiceImpl.stopLocalOnlyHotspot();
3853         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY);
3854         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
3855     }
3856 
3857     /**
3858      * Verify that a call to registerSoftApCallback throws a SecurityException if the caller does
3859      * not have neither NETWORK_SETTINGS nor MAINLINE_NETWORK_STACK permission.
3860      */
3861     @Test(expected = SecurityException.class)
registerSoftApCallbackThrowsSecurityExceptionOnMissingPermissions()3862     public void registerSoftApCallbackThrowsSecurityExceptionOnMissingPermissions() {
3863         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
3864                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
3865         when(mContext.checkPermission(eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK),
3866                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
3867         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false);
3868         mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback);
3869     }
3870 
3871     /**
3872      * Verify that a call to registerSoftApCallback throws an IllegalArgumentException if the
3873      * parameters are not provided.
3874      */
3875     @Test
registerSoftApCallbackThrowsIllegalArgumentExceptionOnInvalidArguments()3876     public void registerSoftApCallbackThrowsIllegalArgumentExceptionOnInvalidArguments() {
3877         try {
3878             mWifiServiceImpl.registerSoftApCallback(null);
3879             fail("expected IllegalArgumentException");
3880         } catch (IllegalArgumentException expected) {
3881         }
3882     }
3883 
3884     /**
3885      * Verify that a call to unregisterSoftApCallback throws a SecurityException if the caller does
3886      * not have neither NETWORK_SETTINGS nor MAINLINE_NETWORK_STACK permission.
3887      */
3888     @Test(expected = SecurityException.class)
unregisterSoftApCallbackThrowsSecurityExceptionOnMissingPermissions()3889     public void unregisterSoftApCallbackThrowsSecurityExceptionOnMissingPermissions() {
3890         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
3891                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
3892         when(mContext.checkPermission(eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK),
3893                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
3894         when(mWifiPermissionsUtil.checkConfigOverridePermission(anyInt())).thenReturn(false);
3895         mWifiServiceImpl.unregisterSoftApCallback(mClientSoftApCallback);
3896     }
3897 
3898     /**
3899      * Verifies that we handle softap callback registration failure if we encounter an exception
3900      * while linking to death.
3901      */
3902     @Test
registerSoftApCallbackFailureOnLinkToDeath()3903     public void registerSoftApCallbackFailureOnLinkToDeath() throws Exception {
3904         doThrow(new RemoteException())
3905                 .when(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
3906         mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback);
3907         mLooper.dispatchAll();
3908         verify(mClientSoftApCallback, never()).onStateChanged(WIFI_AP_STATE_DISABLED, 0);
3909         verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged(
3910                 any(), any(), anyBoolean(), anyBoolean());
3911         verify(mClientSoftApCallback, never()).onCapabilityChanged(any());
3912     }
3913 
3914     /**
3915      * Registers a soft AP callback, then verifies that the current soft AP state and num clients
3916      * are sent to caller immediately after callback is registered.
3917      */
registerSoftApCallbackAndVerify(ISoftApCallback callback)3918     private void registerSoftApCallbackAndVerify(ISoftApCallback callback) throws Exception {
3919         mWifiServiceImpl.registerSoftApCallback(callback);
3920         mLooper.dispatchAll();
3921         verify(callback).onStateChanged(WIFI_AP_STATE_DISABLED, 0);
3922         verify(callback).onConnectedClientsOrInfoChanged(new HashMap<String, SoftApInfo>(),
3923                 new HashMap<String, List<WifiClient>>(), false, true);
3924         verify(callback).onCapabilityChanged(ApConfigUtil.updateCapabilityFromResource(mContext));
3925         // Don't need to invoke callback when register.
3926         verify(callback, never()).onBlockedClientConnecting(any(), anyInt());
3927     }
3928 
3929     /**
3930      * Verify that unregisterSoftApCallback removes callback from registered callbacks list
3931      */
3932     @Test
unregisterSoftApCallbackRemovesCallback()3933     public void unregisterSoftApCallbackRemovesCallback() throws Exception {
3934         registerSoftApCallbackAndVerify(mClientSoftApCallback);
3935 
3936         mWifiServiceImpl.unregisterSoftApCallback(mClientSoftApCallback);
3937         mLooper.dispatchAll();
3938 
3939         reset(mClientSoftApCallback);
3940         mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged(
3941                 mTestSoftApInfos, mTestSoftApClients, false);
3942         mLooper.dispatchAll();
3943         verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged(
3944                 any(), any(), anyBoolean(), anyBoolean());
3945     }
3946 
3947     /**
3948      * Verify that unregisterSoftApCallback is no-op if callback not registered.
3949      */
3950     @Test
unregisterSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching()3951     public void unregisterSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching()
3952             throws Exception {
3953         registerSoftApCallbackAndVerify(mClientSoftApCallback);
3954 
3955         mWifiServiceImpl.unregisterSoftApCallback(mAnotherSoftApCallback);
3956         mLooper.dispatchAll();
3957         mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged(
3958                 mTestSoftApInfos, mTestSoftApClients, false);
3959         mLooper.dispatchAll();
3960         verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged(
3961                 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(false));
3962     }
3963 
3964     /**
3965      * Registers two callbacks, remove one then verify the right callback is being called on events.
3966      */
3967     @Test
correctCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne()3968     public void correctCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne() throws Exception {
3969         WifiClient testWifiClient = new WifiClient(MacAddress.fromString("22:33:44:55:66:77"),
3970                 WIFI_IFACE_NAME2);
3971         mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback);
3972         mLooper.dispatchAll();
3973 
3974         reset(mClientSoftApCallback);
3975         when(mClientSoftApCallback.asBinder()).thenReturn(mAppBinder);
3976         // Change state from default before registering the second callback
3977         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
3978         mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged(
3979                 mTestSoftApInfos, mTestSoftApClients, false);
3980         mStateMachineSoftApCallback.onBlockedClientConnecting(testWifiClient, 0);
3981 
3982 
3983         // Register another callback and verify the new state is returned in the immediate callback
3984         mWifiServiceImpl.registerSoftApCallback(mAnotherSoftApCallback);
3985         mLooper.dispatchAll();
3986         verify(mAnotherSoftApCallback).onStateChanged(WIFI_AP_STATE_ENABLED, 0);
3987         verify(mAnotherSoftApCallback).onConnectedClientsOrInfoChanged(
3988                 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(true));
3989         // Verify only first callback will receive onBlockedClientConnecting since it call after
3990         // first callback register but before another callback register.
3991         verify(mClientSoftApCallback).onBlockedClientConnecting(testWifiClient, 0);
3992         verify(mAnotherSoftApCallback, never()).onBlockedClientConnecting(testWifiClient, 0);
3993 
3994         // unregister the fisrt callback
3995         mWifiServiceImpl.unregisterSoftApCallback(mClientSoftApCallback);
3996         mLooper.dispatchAll();
3997 
3998         // Update soft AP state and verify the remaining callback receives the event
3999         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_FAILED,
4000                 SAP_START_FAILURE_NO_CHANNEL);
4001         mLooper.dispatchAll();
4002         verify(mClientSoftApCallback, never()).onStateChanged(WIFI_AP_STATE_FAILED,
4003                 SAP_START_FAILURE_NO_CHANNEL);
4004         verify(mAnotherSoftApCallback).onStateChanged(WIFI_AP_STATE_FAILED,
4005                 SAP_START_FAILURE_NO_CHANNEL);
4006     }
4007 
4008     /**
4009      * Verify that wifi service registers for callers BinderDeath event
4010      */
4011     @Test
registersForBinderDeathOnRegisterSoftApCallback()4012     public void registersForBinderDeathOnRegisterSoftApCallback() throws Exception {
4013         registerSoftApCallbackAndVerify(mClientSoftApCallback);
4014         verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
4015     }
4016 
4017     /**
4018      * Verify that we un-register the soft AP callback on receiving BinderDied event.
4019      */
4020     @Test
unregistersSoftApCallbackOnBinderDied()4021     public void unregistersSoftApCallbackOnBinderDied() throws Exception {
4022         ArgumentCaptor<IBinder.DeathRecipient> drCaptor =
4023                 ArgumentCaptor.forClass(IBinder.DeathRecipient.class);
4024         registerSoftApCallbackAndVerify(mClientSoftApCallback);
4025         verify(mAppBinder).linkToDeath(drCaptor.capture(), anyInt());
4026 
4027         drCaptor.getValue().binderDied();
4028         mLooper.dispatchAll();
4029         reset(mClientSoftApCallback);
4030         // Verify callback is removed from the list as well
4031         Map<String, List<WifiClient>> mTestSoftApClients = mock(Map.class);
4032         Map<String, SoftApInfo> mTestSoftApInfos = mock(Map.class);
4033         mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged(
4034                 mTestSoftApInfos, mTestSoftApClients, false);
4035         mLooper.dispatchAll();
4036         verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged(
4037                 any(), any(), anyBoolean(), anyBoolean());
4038     }
4039 
4040     /**
4041      * Verify that soft AP callback is called on NumClientsChanged event
4042      */
4043     @Test
callsRegisteredCallbacksOnConnectedClientsChangedEvent()4044     public void callsRegisteredCallbacksOnConnectedClientsChangedEvent() throws Exception {
4045         registerSoftApCallbackAndVerify(mClientSoftApCallback);
4046 
4047         mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged(
4048                 mTestSoftApInfos, mTestSoftApClients, false);
4049         mLooper.dispatchAll();
4050         verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged(
4051                 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(false));
4052     }
4053 
4054     /**
4055      * Verify that soft AP callback is called on SoftApStateChanged event
4056      */
4057     @Test
callsRegisteredCallbacksOnSoftApStateChangedEvent()4058     public void callsRegisteredCallbacksOnSoftApStateChangedEvent() throws Exception {
4059         registerSoftApCallbackAndVerify(mClientSoftApCallback);
4060 
4061         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
4062         mLooper.dispatchAll();
4063         verify(mClientSoftApCallback).onStateChanged(WIFI_AP_STATE_ENABLED, 0);
4064     }
4065 
4066     /**
4067      * Verify that mSoftApState and mSoftApNumClients in WifiServiceImpl are being updated on soft
4068      * Ap events, even when no callbacks are registered.
4069      */
4070     @Test
updatesSoftApStateAndConnectedClientsOnSoftApEvents()4071     public void updatesSoftApStateAndConnectedClientsOnSoftApEvents() throws Exception {
4072         WifiClient testWifiClient = new WifiClient(MacAddress.fromString("22:33:44:55:66:77"),
4073                 WIFI_IFACE_NAME2);
4074         mStateMachineSoftApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
4075         mStateMachineSoftApCallback.onConnectedClientsOrInfoChanged(
4076                 mTestSoftApInfos, mTestSoftApClients, false);
4077         mStateMachineSoftApCallback.onBlockedClientConnecting(testWifiClient, 0);
4078 
4079         // Register callback after num clients and soft AP are changed.
4080         mWifiServiceImpl.registerSoftApCallback(mClientSoftApCallback);
4081         mLooper.dispatchAll();
4082         verify(mClientSoftApCallback).onStateChanged(WIFI_AP_STATE_ENABLED, 0);
4083         verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged(
4084                 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(true));
4085         // Don't need to invoke callback when register.
4086         verify(mClientSoftApCallback, never()).onBlockedClientConnecting(any(), anyInt());
4087     }
4088 
4089     private class IntentFilterMatcher implements ArgumentMatcher<IntentFilter> {
4090         @Override
matches(IntentFilter filter)4091         public boolean matches(IntentFilter filter) {
4092             return filter.hasAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
4093         }
4094     }
4095 
4096     /**
4097      * Verify that onFailed is called for registered LOHS callers on SAP_START_FAILURE_GENERAL.
4098      */
4099     @Test
testRegisteredCallbacksTriggeredOnSoftApFailureGeneric()4100     public void testRegisteredCallbacksTriggeredOnSoftApFailureGeneric() throws Exception {
4101         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4102         mWifiServiceImpl.checkAndStartWifi();
4103         mLooper.dispatchAll();
4104 
4105         verifyApRegistration();
4106 
4107         registerLOHSRequestFull();
4108 
4109         changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_DISABLED, SAP_START_FAILURE_GENERAL);
4110         mLooper.dispatchAll();
4111 
4112         verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC);
4113     }
4114 
4115     /**
4116      * Verify that onFailed is called for registered LOHS callers on SAP_START_FAILURE_NO_CHANNEL.
4117      */
4118     @Test
testRegisteredCallbacksTriggeredOnSoftApFailureNoChannel()4119     public void testRegisteredCallbacksTriggeredOnSoftApFailureNoChannel() throws Exception {
4120         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4121         mWifiServiceImpl.checkAndStartWifi();
4122         mLooper.dispatchAll();
4123 
4124         verifyApRegistration();
4125 
4126         registerLOHSRequestFull();
4127 
4128         changeLohsState(WIFI_AP_STATE_FAILED,
4129                 WIFI_AP_STATE_DISABLED, SAP_START_FAILURE_NO_CHANNEL);
4130 
4131         mLooper.dispatchAll();
4132         verify(mLohsCallback).onHotspotFailed(ERROR_NO_CHANNEL);
4133     }
4134 
4135     /**
4136      * Common setup for starting a LOHS.
4137      */
setupLocalOnlyHotspot()4138     private void setupLocalOnlyHotspot() throws Exception {
4139         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4140         mWifiServiceImpl.checkAndStartWifi();
4141         mLooper.dispatchAll();
4142 
4143         verifyApRegistration();
4144 
4145         registerLOHSRequestFull();
4146 
4147         changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR);
4148         mWifiServiceImpl.updateInterfaceIpState(mLohsInterfaceName, IFACE_IP_MODE_LOCAL_ONLY);
4149         mLooper.dispatchAll();
4150         verify(mLohsCallback).onHotspotStarted(any());
4151     }
4152 
4153     /**
4154      * Verify that onStopped is called for registered LOHS callers when a callback is
4155      * received with WIFI_AP_STATE_DISABLING and LOHS was active.
4156      */
4157     @Test
testRegisteredCallbacksTriggeredOnSoftApDisabling()4158     public void testRegisteredCallbacksTriggeredOnSoftApDisabling() throws Exception {
4159         setupLocalOnlyHotspot();
4160 
4161         changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR);
4162 
4163         mLooper.dispatchAll();
4164         verify(mLohsCallback).onHotspotStopped();
4165     }
4166 
4167 
4168     /**
4169      * Verify that onStopped is called for registered LOHS callers when a callback is
4170      * received with WIFI_AP_STATE_DISABLED and LOHS was enabled.
4171      */
4172     @Test
testRegisteredCallbacksTriggeredOnSoftApDisabled()4173     public void testRegisteredCallbacksTriggeredOnSoftApDisabled() throws Exception {
4174         setupLocalOnlyHotspot();
4175 
4176         changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR);
4177 
4178         mLooper.dispatchAll();
4179         verify(mLohsCallback).onHotspotStopped();
4180     }
4181 
4182     /**
4183      * Verify that no callbacks are called for registered LOHS callers when a callback is
4184      * received and the softap started.
4185      */
4186     @Test
testRegisteredCallbacksNotTriggeredOnSoftApStart()4187     public void testRegisteredCallbacksNotTriggeredOnSoftApStart() throws Exception {
4188         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4189         mWifiServiceImpl.checkAndStartWifi();
4190         mLooper.dispatchAll();
4191 
4192         verifyApRegistration();
4193 
4194         registerLOHSRequestFull();
4195 
4196         changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR);
4197 
4198         mLooper.dispatchAll();
4199         verifyZeroInteractions(ignoreStubs(mLohsCallback));
4200     }
4201 
4202     /**
4203      * Verify that onStopped is called only once for registered LOHS callers when
4204      * callbacks are received with WIFI_AP_STATE_DISABLING and
4205      * WIFI_AP_STATE_DISABLED when LOHS was enabled.
4206      */
4207     @Test
testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApDisabling()4208     public void testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApDisabling() throws Exception {
4209         setupLocalOnlyHotspot();
4210 
4211         changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR);
4212         changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR);
4213 
4214         mLooper.dispatchAll();
4215         verify(mLohsCallback).onHotspotStopped();
4216     }
4217 
4218     /**
4219      * Verify that onFailed is called only once for registered LOHS callers when
4220      * callbacks are received with WIFI_AP_STATE_FAILED twice.
4221      */
4222     @Test
testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApFailsTwice()4223     public void testRegisteredCallbacksTriggeredOnlyOnceWhenSoftApFailsTwice() throws Exception {
4224         setupLocalOnlyHotspot();
4225 
4226         changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC);
4227         changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC);
4228 
4229         mLooper.dispatchAll();
4230         verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC);
4231     }
4232 
4233     /**
4234      * Verify that onFailed is called for all registered LOHS callers when
4235      * callbacks are received with WIFI_AP_STATE_FAILED.
4236      */
4237     @Test
testAllRegisteredCallbacksTriggeredWhenSoftApFails()4238     public void testAllRegisteredCallbacksTriggeredWhenSoftApFails() throws Exception {
4239         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4240         mWifiServiceImpl.checkAndStartWifi();
4241         mLooper.dispatchAll();
4242 
4243         verifyApRegistration();
4244 
4245         // make an additional request for this test
4246         mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo);
4247 
4248         registerLOHSRequestFull();
4249 
4250         changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC);
4251         changeLohsState(WIFI_AP_STATE_FAILED, WIFI_AP_STATE_FAILED, ERROR_GENERIC);
4252 
4253         verify(mRequestInfo).sendHotspotFailedMessage(ERROR_GENERIC);
4254         mLooper.dispatchAll();
4255         verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC);
4256     }
4257 
4258     /**
4259      * Verify that onStopped is called for all registered LOHS callers when
4260      * callbacks are received with WIFI_AP_STATE_DISABLED when LOHS was
4261      * active.
4262      */
4263     @Test
testAllRegisteredCallbacksTriggeredWhenSoftApStops()4264     public void testAllRegisteredCallbacksTriggeredWhenSoftApStops() throws Exception {
4265         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4266         mWifiServiceImpl.checkAndStartWifi();
4267         mLooper.dispatchAll();
4268 
4269         verifyApRegistration();
4270 
4271         mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo);
4272 
4273         registerLOHSRequestFull();
4274 
4275         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
4276         mLooper.dispatchAll();
4277         verify(mRequestInfo).sendHotspotStartedMessage(any());
4278         verify(mLohsCallback).onHotspotStarted(any());
4279 
4280         reset(mRequestInfo);
4281         clearInvocations(mLohsCallback);
4282 
4283         changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR);
4284         changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR);
4285 
4286         verify(mRequestInfo).sendHotspotStoppedMessage();
4287         mLooper.dispatchAll();
4288         verify(mLohsCallback).onHotspotStopped();
4289     }
4290 
4291     /**
4292      * Verify that onFailed is called for all registered LOHS callers when
4293      * callbacks are received with WIFI_AP_STATE_DISABLED when LOHS was
4294      * not active.
4295      */
4296     @Test
testAllRegisteredCallbacksTriggeredWhenSoftApStopsLOHSNotActive()4297     public void testAllRegisteredCallbacksTriggeredWhenSoftApStopsLOHSNotActive() throws Exception {
4298         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4299         mWifiServiceImpl.checkAndStartWifi();
4300         mLooper.dispatchAll();
4301 
4302         verifyApRegistration();
4303 
4304         mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo);
4305         mWifiServiceImpl.registerLOHSForTest(TEST_PID2, mRequestInfo2);
4306 
4307         changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR);
4308         changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR);
4309 
4310         verify(mRequestInfo).sendHotspotFailedMessage(ERROR_GENERIC);
4311         verify(mRequestInfo2).sendHotspotFailedMessage(ERROR_GENERIC);
4312     }
4313 
4314     /**
4315      * Verify that if we do not have registered LOHS requestors and we receive an update that LOHS
4316      * is up and ready for use, we tell WifiController to tear it down.  This can happen if softap
4317      * mode fails to come up properly and we get an onFailed message for a tethering call and we
4318      * had registered callers for LOHS.
4319      */
4320     @Test
testLOHSReadyWithoutRegisteredRequestsStopsSoftApMode()4321     public void testLOHSReadyWithoutRegisteredRequestsStopsSoftApMode() {
4322         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
4323         mLooper.dispatchAll();
4324 
4325         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY);
4326     }
4327 
4328     /**
4329      * Verify that all registered LOHS requestors are notified via a HOTSPOT_STARTED message that
4330      * the hotspot is up and ready to use.
4331      */
4332     @Test
testRegisteredLocalOnlyHotspotRequestorsGetOnStartedCallbackWhenReady()4333     public void testRegisteredLocalOnlyHotspotRequestorsGetOnStartedCallbackWhenReady()
4334             throws Exception {
4335         SoftApConfiguration lohsConfig = createValidSoftApConfiguration();
4336         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
4337                 eq(mContext), eq(null), any())).thenReturn(lohsConfig);
4338         mLooper.startAutoDispatch();
4339         registerLOHSRequestFull();
4340         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
4341         verify(mWifiApConfigStore).generateLocalOnlyHotspotConfig(
4342                 eq(mContext), eq(null), any());
4343         mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo);
4344 
4345         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
4346         mLooper.dispatchAll();
4347         verify(mRequestInfo).sendHotspotStartedMessage(any(SoftApConfiguration.class));
4348 
4349         mLooper.dispatchAll();
4350         verify(mLohsCallback).onHotspotStarted(notNull());
4351     }
4352 
4353     /**
4354      * Verify that if a LOHS is already active, a new call to register a request will trigger the
4355      * onStarted callback.
4356      */
4357     @Test
testRegisterLocalOnlyHotspotRequestAfterAlreadyStartedGetsOnStartedCallback()4358     public void testRegisterLocalOnlyHotspotRequestAfterAlreadyStartedGetsOnStartedCallback()
4359             throws Exception {
4360         mLooper.startAutoDispatch();
4361         mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo);
4362 
4363         changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR);
4364         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
4365 
4366         registerLOHSRequestFull();
4367         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
4368         verify(mLohsCallback).onHotspotStarted(any());
4369     }
4370 
4371     /**
4372      * Verify that if a LOHS request is active and we receive an update with an ip mode
4373      * configuration error, callers are notified via the onFailed callback with the generic
4374      * error and are unregistered.
4375      */
4376     @Test
testCallOnFailedLocalOnlyHotspotRequestWhenIpConfigFails()4377     public void testCallOnFailedLocalOnlyHotspotRequestWhenIpConfigFails() throws Exception {
4378         setupLocalOnlyHotspot();
4379         reset(mActiveModeWarden);
4380 
4381         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_CONFIGURATION_ERROR);
4382         mLooper.dispatchAll();
4383 
4384         verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC);
4385         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY);
4386 
4387         clearInvocations(mLohsCallback);
4388 
4389         // send HOTSPOT_FAILED message should only happen once since the requestor should be
4390         // unregistered
4391         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_CONFIGURATION_ERROR);
4392         mLooper.dispatchAll();
4393         verifyZeroInteractions(ignoreStubs(mLohsCallback));
4394     }
4395 
4396     /**
4397      * Verify that softap mode is stopped for tethering if we receive an update with an ip mode
4398      * configuration error.
4399      */
4400     @Test
testStopSoftApWhenIpConfigFails()4401     public void testStopSoftApWhenIpConfigFails() throws Exception {
4402         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
4403         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_CONFIGURATION_ERROR);
4404         mLooper.dispatchAll();
4405 
4406         verify(mActiveModeWarden).stopSoftAp(IFACE_IP_MODE_TETHERED);
4407     }
4408 
4409     /**
4410      * Verify that if a LOHS request is active and tethering starts, callers are notified on the
4411      * incompatible mode and are unregistered.
4412      */
4413     @Test
testCallOnFailedLocalOnlyHotspotRequestWhenTetheringStarts()4414     public void testCallOnFailedLocalOnlyHotspotRequestWhenTetheringStarts() throws Exception {
4415         mLooper.startAutoDispatch();
4416         registerLOHSRequestFull();
4417 
4418         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
4419         mLooper.dispatchAll();
4420         verify(mLohsCallback).onHotspotStarted(any());
4421         clearInvocations(mLohsCallback);
4422 
4423         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
4424         mLooper.dispatchAll();
4425 
4426         verify(mLohsCallback).onHotspotFailed(ERROR_INCOMPATIBLE_MODE);
4427 
4428         // sendMessage should only happen once since the requestor should be unregistered
4429         clearInvocations(mLohsCallback);
4430 
4431         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
4432         verifyZeroInteractions(ignoreStubs(mLohsCallback));
4433         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
4434     }
4435 
4436     /**
4437      * Verify that if LOHS is disabled, a new call to register a request will not trigger the
4438      * onStopped callback.
4439      */
4440     @Test
testRegisterLocalOnlyHotspotRequestWhenStoppedDoesNotGetOnStoppedCallback()4441     public void testRegisterLocalOnlyHotspotRequestWhenStoppedDoesNotGetOnStoppedCallback()
4442             throws Exception {
4443         mLooper.startAutoDispatch();
4444         registerLOHSRequestFull();
4445         verifyZeroInteractions(ignoreStubs(mLohsCallback));
4446         stopAutoDispatchWithDispatchAllBeforeStopAndIgnoreExceptions(mLooper);
4447     }
4448 
4449     /**
4450      * Verify that if a LOHS was active and then stopped, a new call to register a request will
4451      * not trigger the onStarted callback.
4452      */
4453     @Test
testRegisterLocalOnlyHotspotRequestAfterStoppedNoOnStartedCallback()4454     public void testRegisterLocalOnlyHotspotRequestAfterStoppedNoOnStartedCallback()
4455             throws Exception {
4456         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
4457         mWifiServiceImpl.checkAndStartWifi();
4458         mLooper.dispatchAll();
4459         verifyApRegistration();
4460 
4461         // register a request so we don't drop the LOHS interface ip update
4462         mWifiServiceImpl.registerLOHSForTest(TEST_PID, mRequestInfo);
4463         changeLohsState(WIFI_AP_STATE_ENABLED, WIFI_AP_STATE_DISABLED, HOTSPOT_NO_ERROR);
4464         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_LOCAL_ONLY);
4465         mLooper.dispatchAll();
4466 
4467         registerLOHSRequestFull();
4468         mLooper.dispatchAll();
4469 
4470         verify(mLohsCallback).onHotspotStarted(any());
4471 
4472         clearInvocations(mLohsCallback);
4473 
4474         // now stop the hotspot
4475         changeLohsState(WIFI_AP_STATE_DISABLING, WIFI_AP_STATE_ENABLED, HOTSPOT_NO_ERROR);
4476         changeLohsState(WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING, HOTSPOT_NO_ERROR);
4477         mLooper.dispatchAll();
4478         verify(mLohsCallback).onHotspotStopped();
4479 
4480         clearInvocations(mLohsCallback);
4481 
4482         // now register a new caller - they should not get the onStarted callback
4483         ILocalOnlyHotspotCallback callback2 = mock(ILocalOnlyHotspotCallback.class);
4484         when(callback2.asBinder()).thenReturn(mock(IBinder.class));
4485 
4486         int result = mWifiServiceImpl.startLocalOnlyHotspot(
4487                 callback2, TEST_PACKAGE_NAME, TEST_FEATURE_ID, null, mExtras);
4488         assertEquals(LocalOnlyHotspotCallback.REQUEST_REGISTERED, result);
4489         mLooper.dispatchAll();
4490 
4491         verify(mLohsCallback, never()).onHotspotStarted(any());
4492         verify(mLastCallerInfoManager, atLeastOnce()).put(
4493                 eq(WifiManager.API_START_LOCAL_ONLY_HOTSPOT), anyInt(), anyInt(), anyInt(),
4494                 anyString(), eq(true));
4495     }
4496 
4497     /**
4498      * Verify that a call to startWatchLocalOnlyHotspot is only allowed from callers with the
4499      * signature only NETWORK_SETTINGS permission.
4500      *
4501      * This test is expecting the permission check to enforce the permission and throw a
4502      * SecurityException for callers without the permission.  This exception should be bubbled up to
4503      * the caller of startLocalOnlyHotspot.
4504      */
4505     @Test(expected = SecurityException.class)
testStartWatchLocalOnlyHotspotNotApprovedCaller()4506     public void testStartWatchLocalOnlyHotspotNotApprovedCaller() {
4507         doThrow(new SecurityException()).when(mContext)
4508                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4509                                                 eq("WifiService"));
4510         mWifiServiceImpl.startWatchLocalOnlyHotspot(mLohsCallback);
4511     }
4512 
4513     /**
4514      * Verify that the call to startWatchLocalOnlyHotspot throws the UnsupportedOperationException
4515      * when called until the implementation is complete.
4516      */
4517     @Test(expected = UnsupportedOperationException.class)
testStartWatchLocalOnlyHotspotNotSupported()4518     public void testStartWatchLocalOnlyHotspotNotSupported() {
4519         mWifiServiceImpl.startWatchLocalOnlyHotspot(mLohsCallback);
4520     }
4521 
4522     /**
4523      * Verify that a call to stopWatchLocalOnlyHotspot is only allowed from callers with the
4524      * signature only NETWORK_SETTINGS permission.
4525      */
4526     @Test(expected = SecurityException.class)
testStopWatchLocalOnlyHotspotNotApprovedCaller()4527     public void testStopWatchLocalOnlyHotspotNotApprovedCaller() {
4528         doThrow(new SecurityException()).when(mContext)
4529                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4530                                                 eq("WifiService"));
4531         mWifiServiceImpl.stopWatchLocalOnlyHotspot();
4532     }
4533 
4534     /**
4535      * Verify that the call to stopWatchLocalOnlyHotspot throws the UnsupportedOperationException
4536      * until the implementation is complete.
4537      */
4538     @Test(expected = UnsupportedOperationException.class)
testStopWatchLocalOnlyHotspotNotSupported()4539     public void testStopWatchLocalOnlyHotspotNotSupported() {
4540         mWifiServiceImpl.stopWatchLocalOnlyHotspot();
4541     }
4542 
4543     /**
4544      * Verify that the call to addOrUpdateNetwork for installing Passpoint profile is redirected
4545      * to the Passpoint specific API addOrUpdatePasspointConfiguration.
4546      */
4547     @Test
testAddPasspointProfileViaAddNetwork()4548     public void testAddPasspointProfileViaAddNetwork() throws Exception {
4549         WifiConfiguration config = WifiConfigurationTestUtil.createPasspointNetwork();
4550         config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
4551 
4552         PackageManager pm = mock(PackageManager.class);
4553         when(mContext.getPackageManager()).thenReturn(pm);
4554         when(pm.getApplicationInfoAsUser(any(), anyInt(), any())).thenReturn(mApplicationInfo);
4555         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
4556                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
4557         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
4558                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(true);
4559 
4560         when(mPasspointManager.addOrUpdateProvider(
4561                 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), eq(false),
4562                 eq(true), eq(false))).thenReturn(true);
4563         mLooper.startAutoDispatch();
4564         assertEquals(0,
4565                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
4566         mLooper.stopAutoDispatchAndIgnoreExceptions();
4567         verifyCheckChangePermission(TEST_PACKAGE_NAME);
4568         verify(mPasspointManager).addOrUpdateProvider(
4569                 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), eq(false),
4570                 eq(true), eq(false));
4571         reset(mPasspointManager);
4572 
4573         when(mPasspointManager.addOrUpdateProvider(
4574                 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), anyBoolean(),
4575                 anyBoolean(), eq(false))).thenReturn(false);
4576         mLooper.startAutoDispatch();
4577         assertEquals(-1,
4578                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
4579         mLooper.stopAutoDispatchAndIgnoreExceptions();
4580         verifyCheckChangePermission(TEST_PACKAGE_NAME);
4581         verify(mPasspointManager).addOrUpdateProvider(
4582                 any(PasspointConfiguration.class), anyInt(), eq(TEST_PACKAGE_NAME), anyBoolean(),
4583                 anyBoolean(), eq(false));
4584     }
4585 
4586     /**
4587      * Verify that the call to getAllMatchingPasspointProfilesForScanResults is not redirected to
4588      * specific API getAllMatchingPasspointProfilesForScanResults when the caller doesn't have
4589      * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD.
4590      */
4591     @Test(expected = SecurityException.class)
testGetAllMatchingPasspointProfilesForScanResultsWithoutPermissions()4592     public void testGetAllMatchingPasspointProfilesForScanResultsWithoutPermissions() {
4593         mWifiServiceImpl.getAllMatchingPasspointProfilesForScanResults(new ArrayList<>());
4594     }
4595 
4596     /**
4597      * Verify that the call to getAllMatchingPasspointProfilesForScanResults is redirected to
4598      * specific API getAllMatchingPasspointProfilesForScanResults when the caller have
4599      * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD.
4600      */
4601     @Test
testGetAllMatchingPasspointProfilesForScanResultsWithPermissions()4602     public void testGetAllMatchingPasspointProfilesForScanResultsWithPermissions() {
4603         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4604                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4605         mLooper.startAutoDispatch();
4606         mWifiServiceImpl.getAllMatchingPasspointProfilesForScanResults(createScanResultList());
4607         mLooper.stopAutoDispatchAndIgnoreExceptions();
4608         verify(mPasspointManager).getAllMatchingPasspointProfilesForScanResults(any());
4609     }
4610 
4611     /**
4612      * Verify that the call to getAllMatchingPasspointProfilesForScanResults is not redirected to
4613      * specific API getAllMatchingPasspointProfilesForScanResults when the caller provider invalid
4614      * ScanResult.
4615      */
4616     @Test
testGetAllMatchingPasspointProfilesForScanResultsWithInvalidScanResult()4617     public void testGetAllMatchingPasspointProfilesForScanResultsWithInvalidScanResult() {
4618         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4619                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4620         mLooper.startAutoDispatch();
4621         mWifiServiceImpl.getAllMatchingPasspointProfilesForScanResults(new ArrayList<>());
4622         mLooper.stopAutoDispatchAndIgnoreExceptions();
4623         verify(mPasspointManager, never()).getAllMatchingPasspointProfilesForScanResults(any());
4624     }
4625 
4626     /**
4627      * Verify that the call to getWifiConfigsForPasspointProfiles is not redirected to specific API
4628      * syncGetWifiConfigsForPasspointProfiles when the caller doesn't have NETWORK_SETTINGS
4629      * permissions and NETWORK_SETUP_WIZARD.
4630      */
4631     @Test(expected = SecurityException.class)
testGetWifiConfigsForPasspointProfilesWithoutPermissions()4632     public void testGetWifiConfigsForPasspointProfilesWithoutPermissions() {
4633         mWifiServiceImpl.getWifiConfigsForPasspointProfiles(new ArrayList<>());
4634     }
4635 
4636     /**
4637      * Verify that the call to getMatchingOsuProviders is not redirected to specific API
4638      * syncGetMatchingOsuProviders when the caller doesn't have NETWORK_SETTINGS
4639      * permissions and NETWORK_SETUP_WIZARD.
4640      */
4641     @Test(expected = SecurityException.class)
testGetMatchingOsuProvidersWithoutPermissions()4642     public void testGetMatchingOsuProvidersWithoutPermissions() {
4643         mWifiServiceImpl.getMatchingOsuProviders(new ArrayList<>());
4644     }
4645 
4646     /**
4647      * Verify that the call to getMatchingOsuProviders is redirected to specific API
4648      * syncGetMatchingOsuProviders when the caller have NETWORK_SETTINGS
4649      * permissions and NETWORK_SETUP_WIZARD.
4650      */
4651     @Test
testGetMatchingOsuProvidersWithPermissions()4652     public void testGetMatchingOsuProvidersWithPermissions() {
4653         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4654                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4655         mLooper.startAutoDispatch();
4656         mWifiServiceImpl.getMatchingOsuProviders(createScanResultList());
4657         mLooper.stopAutoDispatch();
4658         verify(mPasspointManager).getMatchingOsuProviders(any());
4659     }
4660 
4661     /**
4662      * Verify that the call to getMatchingOsuProviders is not redirected to specific API
4663      * syncGetMatchingOsuProviders when the caller provider invalid ScanResult
4664      */
4665     @Test
testGetMatchingOsuProvidersWithInvalidScanResult()4666     public void testGetMatchingOsuProvidersWithInvalidScanResult() {
4667         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4668                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4669         mWifiServiceImpl.getMatchingOsuProviders(new ArrayList<>());
4670         mLooper.dispatchAll();
4671         verify(mPasspointManager, never()).getMatchingOsuProviders(any());
4672     }
4673 
4674     /**
4675      * Verify that the call to getMatchingPasspointConfigsForOsuProviders is not redirected to
4676      * specific API syncGetMatchingPasspointConfigsForOsuProviders when the caller doesn't have
4677      * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD.
4678      */
4679     @Test(expected = SecurityException.class)
testGetMatchingPasspointConfigsForOsuProvidersWithoutPermissions()4680     public void testGetMatchingPasspointConfigsForOsuProvidersWithoutPermissions() {
4681         mWifiServiceImpl.getMatchingPasspointConfigsForOsuProviders(new ArrayList<>());
4682     }
4683 
4684     /**
4685      * Verify that the call to startSubscriptionProvisioning is redirected to the Passpoint
4686      * specific API startSubscriptionProvisioning when the caller has the right permissions.
4687      */
4688     @Test
testStartSubscriptionProvisioningWithPermission()4689     public void testStartSubscriptionProvisioningWithPermission() throws Exception {
4690         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4691                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4692         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
4693                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4694 
4695         mLooper.startAutoDispatch();
4696         mWifiServiceImpl.startSubscriptionProvisioning(mOsuProvider, mProvisioningCallback);
4697         mLooper.stopAutoDispatch();
4698         verify(mClientModeManager).syncStartSubscriptionProvisioning(anyInt(),
4699                 eq(mOsuProvider), eq(mProvisioningCallback));
4700     }
4701 
4702     /**
4703      * Verify that the call to startSubscriptionProvisioning is not redirected to the Passpoint
4704      * specific API startSubscriptionProvisioning when the caller provides invalid arguments
4705      */
4706     @Test(expected = IllegalArgumentException.class)
testStartSubscriptionProvisioningWithInvalidProvider()4707     public void testStartSubscriptionProvisioningWithInvalidProvider() throws Exception {
4708         mWifiServiceImpl.startSubscriptionProvisioning(null, mProvisioningCallback);
4709     }
4710 
4711 
4712     /**
4713      * Verify that the call to startSubscriptionProvisioning is not redirected to the Passpoint
4714      * specific API startSubscriptionProvisioning when the caller provides invalid callback
4715      */
4716     @Test(expected = IllegalArgumentException.class)
testStartSubscriptionProvisioningWithInvalidCallback()4717     public void testStartSubscriptionProvisioningWithInvalidCallback() throws Exception {
4718         mWifiServiceImpl.startSubscriptionProvisioning(mOsuProvider, null);
4719     }
4720 
4721     /**
4722      * Verify that the call to startSubscriptionProvisioning is not redirected to the Passpoint
4723      * specific API startSubscriptionProvisioning when the caller doesn't have NETWORK_SETTINGS
4724      * permissions and NETWORK_SETUP_WIZARD.
4725      */
4726     @Test(expected = SecurityException.class)
testStartSubscriptionProvisioningWithoutPermissions()4727     public void testStartSubscriptionProvisioningWithoutPermissions() throws Exception {
4728         when(mContext.checkCallingOrSelfPermission(
4729                 eq(android.Manifest.permission.NETWORK_SETTINGS))).thenReturn(
4730                 PackageManager.PERMISSION_DENIED);
4731         when(mContext.checkSelfPermission(
4732                 eq(android.Manifest.permission.NETWORK_SETUP_WIZARD))).thenReturn(
4733                 PackageManager.PERMISSION_DENIED);
4734 
4735         mWifiServiceImpl.startSubscriptionProvisioning(mOsuProvider, mProvisioningCallback);
4736     }
4737 
4738     /**
4739      * Verify the call to getPasspointConfigurations when the caller doesn't have
4740      * NETWORK_SETTINGS and NETWORK_SETUP_WIZARD permissions.
4741      */
4742     @Test
testGetPasspointConfigurationsWithOutPrivilegedPermissions()4743     public void testGetPasspointConfigurationsWithOutPrivilegedPermissions() {
4744         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
4745         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false);
4746 
4747         mLooper.startAutoDispatch();
4748         mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE_NAME);
4749         mLooper.stopAutoDispatchAndIgnoreExceptions();
4750         verify(mPasspointManager).getProviderConfigs(Binder.getCallingUid(), false);
4751     }
4752 
4753     /**
4754      * Verify that the call to getPasspointConfigurations when the caller does have
4755      * NETWORK_SETTINGS permission.
4756      */
4757     @Test
testGetPasspointConfigurationsWithPrivilegedPermissions()4758     public void testGetPasspointConfigurationsWithPrivilegedPermissions() {
4759         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
4760 
4761         mLooper.startAutoDispatch();
4762         mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE_NAME);
4763         mLooper.stopAutoDispatchAndIgnoreExceptions();
4764         verify(mPasspointManager).getProviderConfigs(Binder.getCallingUid(), true);
4765     }
4766 
4767     /**
4768      * Verify that GetPasspointConfigurations will redirect calls to {@link PasspointManager}
4769      * and returning the result that's returned from {@link PasspointManager}.
4770      */
4771     @Test
testGetPasspointConfigurations()4772     public void testGetPasspointConfigurations() throws Exception {
4773         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
4774 
4775         // Setup expected configs.
4776         List<PasspointConfiguration> expectedConfigs = new ArrayList<>();
4777         PasspointConfiguration config = new PasspointConfiguration();
4778         HomeSp homeSp = new HomeSp();
4779         homeSp.setFqdn("test.com");
4780         config.setHomeSp(homeSp);
4781         expectedConfigs.add(config);
4782 
4783         when(mPasspointManager.getProviderConfigs(anyInt(), anyBoolean()))
4784                 .thenReturn(expectedConfigs);
4785         mLooper.startAutoDispatch();
4786         assertEquals(expectedConfigs, mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE));
4787         mLooper.stopAutoDispatchAndIgnoreExceptions();
4788         reset(mPasspointManager);
4789 
4790         when(mPasspointManager.getProviderConfigs(anyInt(), anyBoolean()))
4791                 .thenReturn(new ArrayList<PasspointConfiguration>());
4792         mLooper.startAutoDispatch();
4793         assertTrue(mWifiServiceImpl.getPasspointConfigurations(TEST_PACKAGE).isEmpty());
4794         mLooper.stopAutoDispatchAndIgnoreExceptions();
4795     }
4796 
4797     /**
4798      * Verify the call to removePasspointConfigurations when the caller doesn't have
4799      * NETWORK_SETTINGS and NETWORK_CARRIER_PROVISIONING permissions.
4800      */
4801     @Test
testRemovePasspointConfigurationWithOutPrivilegedPermissions()4802     public void testRemovePasspointConfigurationWithOutPrivilegedPermissions() {
4803         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
4804         when(mWifiPermissionsUtil.checkNetworkCarrierProvisioningPermission(anyInt())).thenReturn(
4805                 false);
4806 
4807         mLooper.startAutoDispatch();
4808         mWifiServiceImpl.removePasspointConfiguration(TEST_FQDN, TEST_PACKAGE_NAME);
4809         mLooper.stopAutoDispatchAndIgnoreExceptions();
4810         verify(mPasspointManager).removeProvider(Binder.getCallingUid(), false, null,
4811                 TEST_FQDN);
4812     }
4813 
4814     /**
4815      * Verify the call to removePasspointConfigurations when the caller does have
4816      * NETWORK_CARRIER_PROVISIONING permission.
4817      */
4818     @Test
testRemovePasspointConfigurationWithPrivilegedPermissions()4819     public void testRemovePasspointConfigurationWithPrivilegedPermissions() {
4820         when(mWifiPermissionsUtil.checkNetworkCarrierProvisioningPermission(anyInt())).thenReturn(
4821                 true);
4822 
4823         mLooper.startAutoDispatch();
4824         mWifiServiceImpl.removePasspointConfiguration(TEST_FQDN, TEST_PACKAGE_NAME);
4825         mLooper.stopAutoDispatchAndIgnoreExceptions();
4826         verify(mPasspointManager).removeProvider(Binder.getCallingUid(), true, null,
4827                 TEST_FQDN);
4828     }
4829 
4830     /**
4831      * Verify that a call to {@link WifiServiceImpl#restoreBackupData(byte[])} is only allowed from
4832      * callers with the signature only NETWORK_SETTINGS permission.
4833      */
4834     @Test(expected = SecurityException.class)
testRestoreBackupDataNotApprovedCaller()4835     public void testRestoreBackupDataNotApprovedCaller() {
4836         doThrow(new SecurityException()).when(mContext)
4837                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4838                         eq("WifiService"));
4839         mWifiServiceImpl.restoreBackupData(null);
4840         verify(mWifiBackupRestore, never()).retrieveConfigurationsFromBackupData(any(byte[].class));
4841     }
4842 
testRestoreNetworkConfiguration(int configNum, int batchNum, boolean allowOverride)4843     private void testRestoreNetworkConfiguration(int configNum, int batchNum,
4844             boolean allowOverride) {
4845         List<WifiConfiguration> configurations = new ArrayList<>();
4846         when(mResources.getInteger(
4847                 eq(R.integer.config_wifiConfigurationRestoreNetworksBatchNum)))
4848                 .thenReturn(batchNum);
4849         WifiConfiguration config = new WifiConfiguration();
4850         config.SSID = TEST_SSID;
4851         for (int i = 0; i < configNum; i++) {
4852             configurations.add(config);
4853         }
4854         reset(mWifiConfigManager);
4855         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt()))
4856                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
4857         when(mWifiConfigManager.addNetwork(any(), anyInt()))
4858                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
4859         mWifiServiceImpl.restoreNetworks(configurations);
4860         mLooper.dispatchAll();
4861         if (allowOverride) {
4862             verify(mWifiConfigManager, times(configNum)).addOrUpdateNetwork(eq(config), anyInt());
4863             verify(mWifiConfigManager, never()).addNetwork(eq(config), anyInt());
4864         } else {
4865             verify(mWifiConfigManager, never()).addOrUpdateNetwork(eq(config), anyInt());
4866             verify(mWifiConfigManager, times(configNum)).addNetwork(eq(config), anyInt());
4867         }
4868         verify(mWifiConfigManager, times(configNum)).enableNetwork(
4869                 eq(TEST_NETWORK_ID), eq(false), anyInt(), eq(null));
4870         verify(mWifiConfigManager, times(configNum)).allowAutojoin(eq(TEST_NETWORK_ID),
4871                 anyBoolean());
4872     }
4873 
4874     /**
4875      * Verify that a call to
4876      * {@link WifiServiceImpl#restoreNetworks(List)}
4877      * trigeering the process of the network restoration in batches.
4878      */
4879     @Test
testRestoreNetworksWithBatchOverrideDisallowed()4880     public void testRestoreNetworksWithBatchOverrideDisallowed() {
4881         lenient().when(CompatChanges.isChangeEnabled(eq(NOT_OVERRIDE_EXISTING_NETWORKS_ON_RESTORE),
4882                 anyInt())).thenReturn(true);
4883         testRestoreNetworkConfiguration(0 /* configNum */, 50 /* batchNum*/, false);
4884         testRestoreNetworkConfiguration(1 /* configNum */, 50 /* batchNum*/, false);
4885         testRestoreNetworkConfiguration(20 /* configNum */, 50 /* batchNum*/, false);
4886         testRestoreNetworkConfiguration(700 /* configNum */, 50 /* batchNum*/, false);
4887         testRestoreNetworkConfiguration(700 /* configNum */, 0 /* batchNum*/, false);
4888     }
4889 
4890     /**
4891      * Verify that a call to {@link WifiServiceImpl#restoreSupplicantBackupData(byte[], byte[])} is
4892      * only allowed from callers with the signature only NETWORK_SETTINGS permission.
4893      */
4894     @Test(expected = SecurityException.class)
testRestoreSupplicantBackupDataNotApprovedCaller()4895     public void testRestoreSupplicantBackupDataNotApprovedCaller() {
4896         doThrow(new SecurityException()).when(mContext)
4897                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4898                         eq("WifiService"));
4899         mWifiServiceImpl.restoreSupplicantBackupData(null, null);
4900         verify(mWifiBackupRestore, never()).retrieveConfigurationsFromSupplicantBackupData(
4901                 any(byte[].class), any(byte[].class));
4902     }
4903 
4904     /**
4905      * Verify that a call to {@link WifiServiceImpl#retrieveBackupData()} is only allowed from
4906      * callers with the signature only NETWORK_SETTINGS permission.
4907      */
4908     @Test(expected = SecurityException.class)
testRetrieveBackupDataNotApprovedCaller()4909     public void testRetrieveBackupDataNotApprovedCaller() {
4910         doThrow(new SecurityException()).when(mContext)
4911                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4912                         eq("WifiService"));
4913         mWifiServiceImpl.retrieveBackupData();
4914         verify(mWifiBackupRestore, never()).retrieveBackupDataFromConfigurations(any(List.class));
4915     }
4916 
4917     /**
4918      * Verify that a call to {@link WifiServiceImpl#restoreSoftApBackupData(byte[])}
4919      * is only allowed from callers with the signature only NETWORK_SETTINGS permission.
4920      */
4921     @Test(expected = SecurityException.class)
testRestoreSoftApBackupDataNotApprovedCaller()4922     public void testRestoreSoftApBackupDataNotApprovedCaller() {
4923         doThrow(new SecurityException()).when(mContext)
4924                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4925                         eq("WifiService"));
4926         mWifiServiceImpl.restoreSoftApBackupData(null);
4927         verify(mSoftApBackupRestore, never())
4928                 .retrieveSoftApConfigurationFromBackupData(any(byte[].class));
4929     }
4930 
4931     /**
4932      * Verify that a call to {@link WifiServiceImpl#restoreSoftApBackupData(byte[])}
4933      * will call WifiApConfigStore#upgradeSoftApConfiguration and
4934      * WifiApConfigStore#resetToDefaultForUnsupportedConfig.
4935      */
4936     @Test
testRestoreSoftApBackupData()4937     public void testRestoreSoftApBackupData() {
4938         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4939             anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
4940         InOrder inorder = inOrder(mWifiApConfigStore);
4941         SoftApConfiguration testConfig = new SoftApConfiguration.Builder()
4942                 .setSsid("test").build();
4943         byte[] testData = testConfig.toString().getBytes();
4944         when(mSoftApBackupRestore.retrieveSoftApConfigurationFromBackupData(testData))
4945                 .thenReturn(testConfig);
4946         mWifiServiceImpl.restoreSoftApBackupData(testData);
4947         mLooper.dispatchAll();
4948         inorder.verify(mWifiApConfigStore).upgradeSoftApConfiguration(testConfig);
4949         inorder.verify(mWifiApConfigStore).resetToDefaultForUnsupportedConfig(any());
4950         inorder.verify(mWifiApConfigStore).setApConfiguration(any());
4951     }
4952 
4953     /**
4954      * Verify that a call to {@link WifiServiceImpl#retrieveSoftApBackupData()} is only allowed from
4955      * callers with the signature only NETWORK_SETTINGS permission.
4956      */
4957     @Test(expected = SecurityException.class)
testRetrieveSoftApBackupDataNotApprovedCaller()4958     public void testRetrieveSoftApBackupDataNotApprovedCaller() {
4959         doThrow(new SecurityException()).when(mContext)
4960                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4961                         eq("WifiService"));
4962         mWifiServiceImpl.retrieveSoftApBackupData();
4963         verify(mSoftApBackupRestore, never())
4964                 .retrieveBackupDataFromSoftApConfiguration(any(SoftApConfiguration.class));
4965     }
4966 
4967     class TestWifiVerboseLoggingStatusChangedListener extends
4968             IWifiVerboseLoggingStatusChangedListener.Stub {
4969         public int numStatusChangedCounts;
4970         public boolean lastReceivedValue;
4971         @Override
onStatusChanged(boolean enabled)4972         public void onStatusChanged(boolean enabled) throws RemoteException {
4973             numStatusChangedCounts++;
4974             lastReceivedValue = enabled;
4975         }
4976     }
4977 
4978     /**
4979      * Verify that a call to {@link WifiServiceImpl#enableVerboseLogging(int)} is propagated to
4980      * registered {@link IWifiVerboseLoggingStatusChangedListener}. Then, verify that changes are no
4981      * longer propagated when the listener gets unregistered.
4982      */
4983     @Test
testVerboseLoggingListener()4984     public void testVerboseLoggingListener() throws Exception {
4985         doNothing().when(mContext)
4986                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
4987                         eq("WifiService"));
4988         // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset
4989         // before invocation.
4990         reset(mClientModeManager);
4991         TestWifiVerboseLoggingStatusChangedListener listener =
4992                 new TestWifiVerboseLoggingStatusChangedListener();
4993         mWifiServiceImpl.addWifiVerboseLoggingStatusChangedListener(listener);
4994         mLooper.dispatchAll();
4995         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED);
4996         verify(mWifiSettingsConfigStore).put(WIFI_VERBOSE_LOGGING_ENABLED, true);
4997         verify(mActiveModeWarden).enableVerboseLogging(anyBoolean());
4998         assertEquals(1, listener.numStatusChangedCounts);
4999         assertTrue(listener.lastReceivedValue);
5000 
5001         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_DISABLED);
5002         assertEquals(2, listener.numStatusChangedCounts);
5003         assertFalse(listener.lastReceivedValue);
5004 
5005         // unregister the callback and verify no more updates happen.
5006         mWifiServiceImpl.removeWifiVerboseLoggingStatusChangedListener(listener);
5007         mLooper.dispatchAll();
5008         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED);
5009         assertEquals(2, listener.numStatusChangedCounts);
5010         assertFalse(listener.lastReceivedValue);
5011     }
5012 
5013     /**
5014      * Verify an exception is thrown for invalid inputs to
5015      * addWifiVerboseLoggingStatusChangedListener and removeWifiVerboseLoggingStatusChangedListener.
5016      */
5017     @Test
testVerboseLoggingListenerInvalidInput()5018     public void testVerboseLoggingListenerInvalidInput() throws Exception {
5019         try {
5020             mWifiServiceImpl.addWifiVerboseLoggingStatusChangedListener(null);
5021             fail("expected IllegalArgumentException in addWifiVerboseLoggingStatusChangedListener");
5022         } catch (IllegalArgumentException e) {
5023         }
5024         try {
5025             mWifiServiceImpl.removeWifiVerboseLoggingStatusChangedListener(null);
5026             fail("expected IllegalArgumentException in "
5027                     + "removeWifiVerboseLoggingStatusChangedListener");
5028         } catch (IllegalArgumentException e) {
5029         }
5030     }
5031 
5032     /**
5033      * Verify a SecurityException if the caller doesn't have sufficient permissions.
5034      */
5035     @Test
testVerboseLoggingListenerNoPermission()5036     public void testVerboseLoggingListenerNoPermission() throws Exception {
5037         doThrow(new SecurityException()).when(mContext)
5038                 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE),
5039                         eq("WifiService"));
5040         TestWifiVerboseLoggingStatusChangedListener listener =
5041                 new TestWifiVerboseLoggingStatusChangedListener();
5042         try {
5043             mWifiServiceImpl.addWifiVerboseLoggingStatusChangedListener(listener);
5044             fail("expected IllegalArgumentException in addWifiVerboseLoggingStatusChangedListener");
5045         } catch (SecurityException e) {
5046         }
5047         try {
5048             mWifiServiceImpl.removeWifiVerboseLoggingStatusChangedListener(listener);
5049             fail("expected IllegalArgumentException in "
5050                     + "removeWifiVerboseLoggingStatusChangedListener");
5051         } catch (SecurityException e) {
5052         }
5053     }
5054 
5055     /**
5056      * Verify that a call to {@link WifiServiceImpl#enableVerboseLogging(int)} is allowed from
5057      * callers with the signature only NETWORK_SETTINGS permission.
5058      */
5059     @Test
testEnableVerboseLoggingWithNetworkSettingsPermission()5060     public void testEnableVerboseLoggingWithNetworkSettingsPermission() throws Exception {
5061         doNothing().when(mContext)
5062                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5063                         eq("WifiService"));
5064         // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset
5065         // before invocation.
5066         reset(mClientModeManager);
5067         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED);
5068         verify(mWifiSettingsConfigStore).put(WIFI_VERBOSE_LOGGING_ENABLED, true);
5069         verify(mActiveModeWarden).enableVerboseLogging(anyBoolean());
5070     }
5071 
5072     /**
5073      * Verify that setting verbose logging mode to
5074      * {@link WifiManager#VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY)} is allowed from
5075      * callers with the signature only NETWORK_SETTINGS permission.
5076      */
5077     @Test
testEnableShowKeyVerboseLoggingWithNetworkSettingsPermission()5078     public void testEnableShowKeyVerboseLoggingWithNetworkSettingsPermission() throws Exception {
5079         doNothing().when(mContext)
5080                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5081                         eq("WifiService"));
5082         // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset
5083         // before invocation.
5084         reset(mClientModeManager);
5085         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY);
5086         verify(mWifiSettingsConfigStore).put(WIFI_VERBOSE_LOGGING_ENABLED, true);
5087         verify(mActiveModeWarden).enableVerboseLogging(anyBoolean());
5088         verify(mWifiGlobals).setShowKeyVerboseLoggingModeEnabled(eq(true));
5089 
5090         // After auto disable show key mode after the countdown
5091         mLooper.moveTimeForward(WifiServiceImpl.AUTO_DISABLE_SHOW_KEY_COUNTDOWN_MILLIS + 1);
5092         mLooper.dispatchAll();
5093         verify(mWifiGlobals).setShowKeyVerboseLoggingModeEnabled(eq(false));
5094     }
5095 
5096     /**
5097      * Verify that setting verbose logging level to
5098      * {@link WifiManager#VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY)} is not allowed for
5099      * the user build.
5100      */
5101     @Test(expected = SecurityException.class)
testEnableShowKeyVerboseLoggingNotAllowedForUserBuild()5102     public void testEnableShowKeyVerboseLoggingNotAllowedForUserBuild() throws Exception {
5103         when(mBuildProperties.isUserBuild()).thenReturn(true);
5104         doNothing().when(mContext)
5105                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5106                         eq("WifiService"));
5107         // Verbose logging is enabled first in the constructor for WifiServiceImpl, so reset
5108         // before invocation.
5109         reset(mClientModeManager);
5110         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY);
5111     }
5112 
5113     /**
5114      * Verify that a call to {@link WifiServiceImpl#enableVerboseLogging(int)} is not allowed from
5115      * callers without the signature only NETWORK_SETTINGS permission.
5116      */
5117     @Test(expected = SecurityException.class)
testEnableVerboseLoggingWithNoNetworkSettingsPermission()5118     public void testEnableVerboseLoggingWithNoNetworkSettingsPermission() {
5119         doThrow(new SecurityException()).when(mContext)
5120                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5121                         eq("WifiService"));
5122         // Vebose logging is enabled first in the constructor for WifiServiceImpl, so reset
5123         // before invocation.
5124         reset(mClientModeManager);
5125         mWifiServiceImpl.enableVerboseLogging(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED);
5126         verify(mWifiSettingsConfigStore, never()).put(
5127                 WIFI_VERBOSE_LOGGING_ENABLED, anyBoolean());
5128         verify(mActiveModeWarden, never()).enableVerboseLogging(anyBoolean());
5129     }
5130 
5131     /**
5132      * Verify that the CONNECT_NETWORK message received from an app without
5133      * one of the privileged permission is rejected with a security exception.
5134      */
5135     @Test
testConnectNetworkWithoutPrivilegedPermission()5136     public void testConnectNetworkWithoutPrivilegedPermission() throws Exception {
5137         try {
5138             mWifiServiceImpl.connect(mock(WifiConfiguration.class), TEST_NETWORK_ID,
5139                     mock(IActionListener.class), TEST_PACKAGE_NAME);
5140             fail();
5141         } catch (SecurityException e) {
5142             mLooper.dispatchAll();
5143             verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
5144         }
5145     }
5146 
5147     /**
5148      * Verify that the FORGET_NETWORK message received from an app without
5149      * one of the privileged permission is rejected with a security exception.
5150      */
5151     @Test
testForgetNetworkWithoutPrivilegedPermission()5152     public void testForgetNetworkWithoutPrivilegedPermission() throws Exception {
5153         try {
5154             mWifiServiceImpl.forget(TEST_NETWORK_ID, mock(IActionListener.class));
5155             fail();
5156         } catch (SecurityException e) {
5157             mLooper.dispatchAll();
5158             verify(mWifiConfigManager, never()).removeNetwork(anyInt(), anyInt(), any());
5159         }
5160     }
5161 
5162     /**
5163      * Verify that the SAVE_NETWORK message received from an app without
5164      * one of the privileged permission is rejected with a security exception.
5165      */
5166     @Test
testSaveNetworkWithoutPrivilegedPermission()5167     public void testSaveNetworkWithoutPrivilegedPermission() throws Exception {
5168         try {
5169             mWifiServiceImpl.save(mock(WifiConfiguration.class), mock(IActionListener.class),
5170                     TEST_PACKAGE_NAME);
5171             fail();
5172         } catch (SecurityException e) {
5173             mLooper.dispatchAll();
5174             verify(mWifiConfigManager, never()).updateBeforeSaveNetwork(any(), anyInt(), any());
5175         }
5176     }
5177 
5178     /**
5179      * Verify that the CONNECT_NETWORK message received from an app with
5180      * one of the privileged permission is forwarded to ClientModeManager.
5181      */
5182     @Test
testConnectNetworkWithPrivilegedPermission()5183     public void testConnectNetworkWithPrivilegedPermission() throws Exception {
5184         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5185             anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5186         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5187         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt()))
5188                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
5189         WifiConfiguration config = new WifiConfiguration();
5190         config.SSID = TEST_SSID;
5191         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5192         mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class),
5193                 TEST_PACKAGE_NAME);
5194         mLooper.dispatchAll();
5195         verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt());
5196         verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class),
5197                 any(ActionListenerWrapper.class), anyInt(), any());
5198         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK),
5199                 anyInt());
5200         verify(mLastCallerInfoManager).put(eq(WifiManager.API_CONNECT_CONFIG), anyInt(),
5201                 anyInt(), anyInt(), anyString(), eq(true));
5202     }
5203 
5204     /**
5205      * Verify that the CONNECT_NETWORK message received from an app with
5206      * one of the privileged permission will stop secondary CMMs that are alraedy connected to
5207      * the same network before initiating the connection.
5208      */
5209     @Test
testConnectNetworkStopSecondaryCmmOnSameNetwork()5210     public void testConnectNetworkStopSecondaryCmmOnSameNetwork() throws Exception {
5211         // grant permissions to access WifiServiceImpl#connect
5212         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5213                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5214         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5215         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt()))
5216                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
5217         WifiConfiguration config = WifiConfigurationTestUtil.createWpa2Wpa3EnterpriseNetwork();
5218         config.SSID = TEST_SSID;
5219         WifiConfiguration localOnlyConfig = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
5220         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5221 
5222         // Mock ActiveModeWarden to return a primary CMM and a secondary CMM to be already
5223         // connected to the target network.
5224         List<ClientModeManager> clientModeManagers = new ArrayList<>();
5225         ClientModeManager primaryCmm = mock(ClientModeManager.class);
5226         when(primaryCmm.getRole()).thenReturn(ROLE_CLIENT_PRIMARY);
5227         ClientModeManager localOnlyCmm = mock(ClientModeManager.class);
5228         when(localOnlyCmm.getRole()).thenReturn(ROLE_CLIENT_LOCAL_ONLY);
5229         when(localOnlyCmm.isConnected()).thenReturn(true);
5230         when(localOnlyCmm.getConnectedWifiConfiguration()).thenReturn(localOnlyConfig);
5231         clientModeManagers.add(primaryCmm);
5232         clientModeManagers.add(localOnlyCmm);
5233         when(mActiveModeWarden.getClientModeManagers()).thenReturn(clientModeManagers);
5234 
5235         // Verify that the localOnlyCmm is not stopped since security type is different
5236         mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class),
5237                 TEST_PACKAGE_NAME);
5238         mLooper.dispatchAll();
5239         verify(primaryCmm, never()).stop();
5240         verify(localOnlyCmm, never()).stop();
5241         verify(mWifiConfigManager).addOrUpdateNetwork(eq(config), anyInt());
5242         verify(mConnectHelper).connectToNetwork(any(NetworkUpdateResult.class),
5243                 any(ActionListenerWrapper.class), anyInt(), any());
5244         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK),
5245                 anyInt());
5246 
5247         // update mock so that the localOnlyConfig matches with target config.
5248         localOnlyConfig = WifiConfigurationTestUtil.createWpa3EnterpriseNetwork(TEST_SSID);
5249         when(localOnlyCmm.getConnectedWifiConfiguration()).thenReturn(localOnlyConfig);
5250 
5251         // Verify that the localOnlyCmm is stopped this time
5252         mWifiServiceImpl.connect(config, TEST_NETWORK_ID, mock(IActionListener.class),
5253                 TEST_PACKAGE_NAME);
5254         mLooper.dispatchAll();
5255         verify(primaryCmm, never()).stop();
5256         verify(localOnlyCmm).stop();
5257         verify(mWifiConfigManager, times(2)).addOrUpdateNetwork(eq(config), anyInt());
5258         verify(mConnectHelper, times(2)).connectToNetwork(any(NetworkUpdateResult.class),
5259                 any(ActionListenerWrapper.class), anyInt(), any());
5260         verify(mWifiMetrics, times(2)).logUserActionEvent(
5261                 eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK), anyInt());
5262     }
5263 
5264     @Test
connectToNewNetwork_success()5265     public void connectToNewNetwork_success() throws Exception {
5266         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5267                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5268         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5269         NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID);
5270         when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt()))
5271                 .thenReturn(result);
5272         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5273 
5274         mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID,
5275                 mActionListener, TEST_PACKAGE_NAME);
5276         mLooper.dispatchAll();
5277 
5278         ArgumentCaptor<WifiConfiguration> configCaptor =
5279                 ArgumentCaptor.forClass(WifiConfiguration.class);
5280         verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt());
5281         assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID);
5282 
5283         verify(mConnectHelper).connectToNetwork(eq(result), any(), anyInt(), any());
5284         verify(mContextAsUser).sendBroadcastWithMultiplePermissions(
5285                 mIntentCaptor.capture(),
5286                 aryEq(new String[]{
5287                         android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE,
5288                         android.Manifest.permission.ACCESS_FINE_LOCATION,
5289                 }));
5290 
5291         Intent intent = mIntentCaptor.getValue();
5292         assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION);
5293         assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID))
5294                 .isEqualTo(TEST_SSID);
5295         assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1))
5296                 .isEqualTo(WifiManager.WIFI_CREDENTIAL_SAVED);
5297     }
5298 
5299     @Test
connectToNewNetwork_failure()5300     public void connectToNewNetwork_failure() throws Exception {
5301         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5302                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5303         when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt()))
5304                 .thenReturn(NetworkUpdateResult.makeFailed());
5305         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5306 
5307         mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID,
5308                 mActionListener, TEST_PACKAGE_NAME);
5309         mLooper.dispatchAll();
5310 
5311         verify(mWifiConfigManager).addOrUpdateNetwork(eq(mWifiConfig), anyInt());
5312 
5313         verify(mClientModeManager, never()).connectNetwork(any(), any(), anyInt(), any());
5314         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5315         verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5316         verify(mActionListener, never()).onSuccess();
5317     }
5318 
5319     @Test
connectToExistingNetwork()5320     public void connectToExistingNetwork() throws Exception {
5321         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5322                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5323         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5324         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5325         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5326 
5327         mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME);
5328         mLooper.dispatchAll();
5329 
5330         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt());
5331 
5332         verify(mConnectHelper).connectToNetwork(
5333                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
5334         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5335         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt());
5336         verify(mLastCallerInfoManager).put(eq(WifiManager.API_CONNECT_NETWORK_ID), anyInt(),
5337                 anyInt(), anyInt(), anyString(), eq(true));
5338     }
5339 
5340     @Test
connectToSimBasedNetworkWhenSimPresent()5341     public void connectToSimBasedNetworkWhenSimPresent() {
5342         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
5343                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
5344         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5345                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5346         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5347         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5348         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5349         when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID);
5350         when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(true);
5351 
5352         mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME);
5353         mLooper.dispatchAll();
5354 
5355         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt());
5356 
5357         verify(mConnectHelper).connectToNetwork(
5358                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
5359         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5360         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt());
5361     }
5362 
5363     @Test
connectToSimBasedNetworkWhenSimAbsent()5364     public void connectToSimBasedNetworkWhenSimAbsent() {
5365         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
5366                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
5367         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5368                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5369         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5370         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5371         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5372         when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID);
5373         when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(false);
5374 
5375         mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME);
5376         mLooper.dispatchAll();
5377 
5378         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt());
5379 
5380         verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
5381         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5382         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt());
5383     }
5384 
5385     @Test
connectToSimBasedNetworkRequiresImsiEncryptionButNotReady()5386     public void connectToSimBasedNetworkRequiresImsiEncryptionButNotReady() {
5387         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
5388                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
5389         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5390                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5391         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5392         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5393         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5394         when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID);
5395         when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(false);
5396         when(mWifiCarrierInfoManager.requiresImsiEncryption(TEST_SUB_ID)).thenReturn(true);
5397         when(mWifiCarrierInfoManager.isImsiEncryptionInfoAvailable(TEST_SUB_ID)).thenReturn(false);
5398 
5399         mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME);
5400         mLooper.dispatchAll();
5401 
5402         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt());
5403 
5404         verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
5405         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5406         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt());
5407     }
5408 
5409     @Test
connectToSimBasedNetworkOobPseudonymEnabledButNotAvailable()5410     public void connectToSimBasedNetworkOobPseudonymEnabledButNotAvailable() {
5411         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
5412                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
5413         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5414                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5415         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5416         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5417         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5418         when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID);
5419         when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(true);
5420         when(mWifiCarrierInfoManager.isOobPseudonymFeatureEnabled(anyInt())).thenReturn(true);
5421         when(mWifiPseudonymManager.getValidPseudonymInfo(anyInt())).thenReturn(Optional.empty());
5422 
5423         mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME);
5424         mLooper.dispatchAll();
5425 
5426         verify(mWifiPseudonymManager).retrievePseudonymOnFailureTimeoutExpired(any());
5427         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(), anyInt());
5428 
5429         verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
5430         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5431         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt());
5432     }
5433 
5434     @Test
connectToSimBasedNetworkWhenOobPseudonymEnabledAndAvailable()5435     public void connectToSimBasedNetworkWhenOobPseudonymEnabledAndAvailable() {
5436         WifiConfiguration config = WifiConfigurationTestUtil.createEapNetwork(
5437                 WifiEnterpriseConfig.Eap.SIM, WifiEnterpriseConfig.Phase2.NONE);
5438         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5439                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5440         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5441         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5442         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
5443         when(mWifiCarrierInfoManager.getBestMatchSubscriptionId(any())).thenReturn(TEST_SUB_ID);
5444         when(mWifiCarrierInfoManager.isSimReady(TEST_SUB_ID)).thenReturn(true);
5445         when(mWifiCarrierInfoManager.isOobPseudonymFeatureEnabled(anyInt())).thenReturn(true);
5446         when(mWifiPseudonymManager.getValidPseudonymInfo(anyInt()))
5447                 .thenReturn(Optional.of(mock(PseudonymInfo.class)));
5448 
5449         mWifiServiceImpl.connect(null, TEST_NETWORK_ID, mActionListener, TEST_PACKAGE_NAME);
5450         mLooper.dispatchAll();
5451 
5452         verify(mWifiPseudonymManager).updateWifiConfiguration(any());
5453         verify(mConnectHelper).connectToNetwork(
5454                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
5455         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5456         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_MANUAL_CONNECT), anyInt());
5457     }
5458 
5459     /**
5460      * Verify that connecting to an admin restricted network fails to connect but saves the network
5461      */
5462     @Test
connectToAdminRestrictedNetwork_failure()5463     public void connectToAdminRestrictedNetwork_failure() throws Exception {
5464         assumeTrue(SdkLevel.isAtLeastT());
5465         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5466                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5467         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5468         NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID);
5469         when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt()))
5470                 .thenReturn(result);
5471         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5472         when(mWifiPermissionsUtil.isAdminRestrictedNetwork(mWifiConfig)).thenReturn(true);
5473 
5474         mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID,
5475                 mActionListener, TEST_PACKAGE_NAME);
5476         mLooper.dispatchAll();
5477 
5478         ArgumentCaptor<WifiConfiguration> configCaptor =
5479                 ArgumentCaptor.forClass(WifiConfiguration.class);
5480         verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt());
5481         assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID);
5482 
5483         verify(mWifiConfigManager).addOrUpdateNetwork(eq(mWifiConfig), anyInt());
5484         verify(mClientModeManager, never()).connectNetwork(any(), any(), anyInt(), any());
5485         verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5486         verify(mActionListener, never()).onSuccess();
5487     }
5488 
5489     /**
5490      * Verify that the SAVE_NETWORK message received from an app with
5491      * one of the privileged permission is forwarded to ClientModeManager.
5492      */
5493     @Test
testSaveNetworkWithPrivilegedPermission()5494     public void testSaveNetworkWithPrivilegedPermission() throws Exception {
5495         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5496             anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5497         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5498         when(mWifiConfigManager.updateBeforeSaveNetwork(any(), anyInt(), any()))
5499                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
5500         mWifiServiceImpl.save(mock(WifiConfiguration.class), mock(IActionListener.class),
5501                 TEST_PACKAGE_NAME);
5502         mLooper.dispatchAll();
5503         verify(mWifiConfigManager).updateBeforeSaveNetwork(any(WifiConfiguration.class), anyInt(),
5504                 any());
5505         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_ADD_OR_UPDATE_NETWORK),
5506                 anyInt());
5507         verify(mLastCallerInfoManager).put(eq(WifiManager.API_SAVE), anyInt(),
5508                 anyInt(), anyInt(), anyString(), eq(true));
5509     }
5510 
5511     @Test
saveNetwork_success()5512     public void saveNetwork_success() throws Exception {
5513         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5514                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5515         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5516 
5517         NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID);
5518         when(mWifiConfigManager.updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any()))
5519                 .thenReturn(result);
5520 
5521         mWifiServiceImpl.save(mWifiConfig, mActionListener, TEST_PACKAGE_NAME);
5522         mLooper.dispatchAll();
5523 
5524         verify(mWifiConfigManager).updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any());
5525 
5526         verify(mClientModeManager).saveNetwork(eq(result), any(), anyInt(), any());
5527         verify(mContextAsUser).sendBroadcastWithMultiplePermissions(
5528                 mIntentCaptor.capture(),
5529                 aryEq(new String[]{
5530                         android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE,
5531                         android.Manifest.permission.ACCESS_FINE_LOCATION,
5532                 }));
5533 
5534         Intent intent = mIntentCaptor.getValue();
5535         assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION);
5536         assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID))
5537                 .isEqualTo(TEST_SSID);
5538         assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1))
5539                 .isEqualTo(WifiManager.WIFI_CREDENTIAL_SAVED);
5540     }
5541 
5542     @Test
saveNetwork_failure()5543     public void saveNetwork_failure() throws Exception {
5544         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5545                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5546         when(mWifiConfigManager.updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any()))
5547                 .thenReturn(NetworkUpdateResult.makeFailed());
5548         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5549 
5550         mWifiServiceImpl.save(mWifiConfig, mActionListener, TEST_PACKAGE_NAME);
5551         mLooper.dispatchAll();
5552 
5553         verify(mWifiConfigManager).updateBeforeSaveNetwork(eq(mWifiConfig), anyInt(), any());
5554 
5555         verify(mClientModeManager, never()).saveNetwork(any(), any(), anyInt(), any());
5556         verify(mContext, never()).sendBroadcastWithMultiplePermissions(any(), any());
5557         verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5558         verify(mActionListener, never()).onSuccess();
5559     }
5560 
5561     /**
5562      * Verify that the FORGET_NETWORK message received from an app with
5563      * one of the privileged permission is forwarded to ClientModeManager.
5564      */
5565     @Test
testForgetNetworkWithPrivilegedPermission()5566     public void testForgetNetworkWithPrivilegedPermission() throws Exception {
5567         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5568             anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5569         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
5570         when(mWifiConfigManager.removeNetwork(anyInt(), anyInt(), any())).thenReturn(true);
5571         mWifiServiceImpl.forget(TEST_NETWORK_ID, mock(IActionListener.class));
5572 
5573         InOrder inOrder = inOrder(mWifiConfigManager, mWifiMetrics);
5574         inOrder.verify(mWifiMetrics).logUserActionEvent(
5575                 UserActionEvent.EVENT_FORGET_WIFI, TEST_NETWORK_ID);
5576 
5577         mLooper.dispatchAll();
5578         inOrder.verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt(), any());
5579         verify(mLastCallerInfoManager).put(eq(WifiManager.API_FORGET), anyInt(),
5580                 anyInt(), anyInt(), anyString(), eq(true));
5581     }
5582 
5583     @Test
forgetNetwork_success()5584     public void forgetNetwork_success() throws Exception {
5585         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5586                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5587         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5588         when(mWifiConfigManager.removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any()))
5589                 .thenReturn(true);
5590         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5591 
5592         mWifiServiceImpl.forget(TEST_NETWORK_ID, mActionListener);
5593         mLooper.dispatchAll();
5594 
5595         verify(mWifiConfigManager).removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any());
5596         verify(mActionListener).onSuccess();
5597         verify(mActionListener, never())
5598                 .onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5599 
5600         verify(mContextAsUser).sendBroadcastWithMultiplePermissions(
5601                 mIntentCaptor.capture(),
5602                 aryEq(new String[]{
5603                         android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE,
5604                         android.Manifest.permission.ACCESS_FINE_LOCATION,
5605                 }));
5606 
5607         Intent intent = mIntentCaptor.getValue();
5608         assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION);
5609         assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID))
5610                 .isEqualTo(TEST_SSID);
5611         assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1))
5612                 .isEqualTo(WifiManager.WIFI_CREDENTIAL_FORGOT);
5613     }
5614 
5615     @Test
forgetNetwork_successNoLocation_dontBroadcastSsid()5616     public void forgetNetwork_successNoLocation_dontBroadcastSsid() throws Exception {
5617         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false);
5618 
5619         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5620                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5621         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5622         when(mWifiConfigManager.removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any()))
5623                 .thenReturn(true);
5624 
5625         mWifiServiceImpl.forget(TEST_NETWORK_ID, mActionListener);
5626         mLooper.dispatchAll();
5627 
5628         verify(mWifiConfigManager).removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any());
5629         verify(mActionListener).onSuccess();
5630         verify(mActionListener, never())
5631                 .onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5632 
5633         verify(mContextAsUser).sendBroadcastWithMultiplePermissions(
5634                 mIntentCaptor.capture(),
5635                 aryEq(new String[]{
5636                         android.Manifest.permission.RECEIVE_WIFI_CREDENTIAL_CHANGE,
5637                         android.Manifest.permission.ACCESS_FINE_LOCATION,
5638                 }));
5639 
5640         Intent intent = mIntentCaptor.getValue();
5641         assertThat(intent.getAction()).isEqualTo(WifiManager.WIFI_CREDENTIAL_CHANGED_ACTION);
5642         // SSID is null if location is disabled
5643         assertThat(intent.getStringExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_SSID)).isNull();
5644         assertThat(intent.getIntExtra(WifiManager.EXTRA_WIFI_CREDENTIAL_EVENT_TYPE, -1))
5645                 .isEqualTo(WifiManager.WIFI_CREDENTIAL_FORGOT);
5646     }
5647 
5648     @Test
forgetNetwork_failed()5649     public void forgetNetwork_failed() throws Exception {
5650         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5651                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5652         when(mWifiConfigManager.removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any()))
5653                 .thenReturn(false);
5654         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5655 
5656         mWifiServiceImpl.forget(TEST_NETWORK_ID, mActionListener);
5657         mLooper.dispatchAll();
5658 
5659         verify(mActionListener, never()).onSuccess();
5660         verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5661         verify(mWifiConfigManager).removeNetwork(eq(TEST_NETWORK_ID), anyInt(), any());
5662         verify(mContextAsUser, never()).sendBroadcastWithMultiplePermissions(any(), any());
5663     }
5664 
5665     /**
5666      * Verify that connecting to a supported security type network succeeds
5667      */
5668     @Test
connectToSupportedSecurityTypeNetwork_success()5669     public void connectToSupportedSecurityTypeNetwork_success() throws Exception {
5670         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5671                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5672         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5673         NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID);
5674         when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt()))
5675                 .thenReturn(result);
5676         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5677         when(mWifiGlobals.isDeprecatedSecurityTypeNetwork(mWifiConfig)).thenReturn(false);
5678 
5679         mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID,
5680                 mActionListener, TEST_PACKAGE_NAME);
5681         mLooper.dispatchAll();
5682 
5683         ArgumentCaptor<WifiConfiguration> configCaptor =
5684                 ArgumentCaptor.forClass(WifiConfiguration.class);
5685         verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt());
5686         assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID);
5687 
5688         verify(mConnectHelper).connectToNetwork(eq(result), any(), anyInt(), any());
5689     }
5690 
5691     /**
5692      * Verify that connecting to a deprecated security type network fails,
5693      * but saves the network instead
5694      */
5695     @Test
connectToDeprecatedSecurityTypeNetwork_failure()5696     public void connectToDeprecatedSecurityTypeNetwork_failure() throws Exception {
5697         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5698                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5699         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
5700         NetworkUpdateResult result = new NetworkUpdateResult(TEST_NETWORK_ID);
5701         when(mWifiConfigManager.addOrUpdateNetwork(eq(mWifiConfig), anyInt()))
5702                 .thenReturn(result);
5703         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(mWifiConfig);
5704         when(mWifiGlobals.isDeprecatedSecurityTypeNetwork(mWifiConfig)).thenReturn(true);
5705 
5706         mWifiServiceImpl.connect(mWifiConfig, WifiConfiguration.INVALID_NETWORK_ID,
5707                 mActionListener, TEST_PACKAGE_NAME);
5708         mLooper.dispatchAll();
5709 
5710         ArgumentCaptor<WifiConfiguration> configCaptor =
5711                 ArgumentCaptor.forClass(WifiConfiguration.class);
5712         verify(mWifiConfigManager).addOrUpdateNetwork(configCaptor.capture(), anyInt());
5713         assertThat(configCaptor.getValue().networkId).isEqualTo(TEST_NETWORK_ID);
5714 
5715         verify(mWifiConfigManager).addOrUpdateNetwork(eq(mWifiConfig), anyInt());
5716         verify(mClientModeManager, never()).connectNetwork(any(), any(), anyInt(), any());
5717         verify(mActionListener).onFailure(WifiManager.ActionListener.FAILURE_INTERNAL_ERROR);
5718         verify(mActionListener, never()).onSuccess();
5719     }
5720 
5721     /**
5722      * Tests the scenario when a scan request arrives while the device is idle. In this case
5723      * the scan is done when idle mode ends.
5724      */
5725     @Test
testHandleDelayedScanAfterIdleMode()5726     public void testHandleDelayedScanAfterIdleMode() throws Exception {
5727         when(mSettingsStore.isWifiToggleEnabled()).thenReturn(false);
5728         mWifiServiceImpl.checkAndStartWifi();
5729         mWifiServiceImpl.handleBootCompleted();
5730         mLooper.dispatchAll();
5731         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5732                 (IntentFilter) argThat(new IdleModeIntentMatcher()),
5733                 isNull(),
5734                 any(Handler.class));
5735 
5736         // Tell the wifi service that the device became idle.
5737         when(mPowerManager.isDeviceIdleMode()).thenReturn(true);
5738         TestUtil.sendIdleModeChanged(mBroadcastReceiverCaptor.getValue(), mContext);
5739 
5740         // Send a scan request while the device is idle.
5741         mWifiThreadRunner.prepareForAutoDispatch();
5742         mLooper.startAutoDispatch();
5743         assertFalse(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID));
5744         mLooper.stopAutoDispatch();
5745         // No scans must be made yet as the device is idle.
5746         verify(mScanRequestProxy, never()).startScan(Process.myUid(), SCAN_PACKAGE_NAME);
5747 
5748         // Tell the wifi service that idle mode ended.
5749         when(mPowerManager.isDeviceIdleMode()).thenReturn(false);
5750         mWifiThreadRunner.prepareForAutoDispatch();
5751         mLooper.startAutoDispatch();
5752         TestUtil.sendIdleModeChanged(mBroadcastReceiverCaptor.getValue(), mContext);
5753         mLooper.stopAutoDispatch();
5754 
5755         // Must scan now.
5756         verify(mScanRequestProxy).startScan(Process.myUid(), TEST_PACKAGE_NAME);
5757         // The app ops check is executed with this package's identity (not the identity of the
5758         // original remote caller who requested the scan while idle).
5759         verify(mAppOpsManager).noteOp(
5760                 AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
5761 
5762         // Send another scan request. The device is not idle anymore, so it must be executed
5763         // immediately.
5764         mWifiThreadRunner.prepareForAutoDispatch();
5765         mLooper.startAutoDispatch();
5766         assertTrue(mWifiServiceImpl.startScan(SCAN_PACKAGE_NAME, TEST_FEATURE_ID));
5767         mLooper.stopAutoDispatch();
5768         verify(mScanRequestProxy).startScan(Process.myUid(), SCAN_PACKAGE_NAME);
5769     }
5770 
5771     /**
5772      * Verify that if the caller has NETWORK_SETTINGS permission, then it doesn't need
5773      * CHANGE_WIFI_STATE permission.
5774      */
5775     @Test
testDisconnectWithNetworkSettingsPerm()5776     public void testDisconnectWithNetworkSettingsPerm() throws Exception {
5777         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
5778                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
5779         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
5780                 android.Manifest.permission.CHANGE_WIFI_STATE, "WifiService");
5781         doThrow(new SecurityException()).when(mAppOpsManager)
5782                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
5783         assertTrue(mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME));
5784         mLooper.dispatchAll();
5785         verify(mClientModeManager).disconnect();
5786     }
5787 
5788     /**
5789      * Verify that if the caller doesn't have NETWORK_SETTINGS permission, it could still
5790      * get access with the CHANGE_WIFI_STATE permission.
5791      */
5792     @Test
testDisconnectWithChangeWifiStatePerm()5793     public void testDisconnectWithChangeWifiStatePerm() throws Exception {
5794         assertFalse(mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME));
5795         mLooper.dispatchAll();
5796         verifyCheckChangePermission(TEST_PACKAGE_NAME);
5797         verify(mClientModeManager, never()).disconnect();
5798     }
5799 
5800     /**
5801      * Verify that the operation fails if the caller has neither NETWORK_SETTINGS or
5802      * CHANGE_WIFI_STATE permissions.
5803      */
5804     @Test
testDisconnectRejected()5805     public void testDisconnectRejected() throws Exception {
5806         doThrow(new SecurityException()).when(mAppOpsManager)
5807                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
5808         try {
5809             mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME);
5810             fail();
5811         } catch (SecurityException e) {
5812 
5813         }
5814         verifyCheckChangePermission(TEST_PACKAGE_NAME);
5815         verify(mClientModeManager, never()).disconnect();
5816     }
5817 
5818     @Test
testPackageFullyRemovedBroadcastHandling()5819     public void testPackageFullyRemovedBroadcastHandling() throws Exception {
5820         mWifiServiceImpl.checkAndStartWifi();
5821         mLooper.dispatchAll();
5822         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5823                 argThat((IntentFilter filter) ->
5824                         filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
5825                                 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED)
5826                                 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)),
5827                 isNull(),
5828                 any(Handler.class));
5829         int uid = TEST_UID;
5830         String packageName = TEST_PACKAGE_NAME;
5831         doThrow(new PackageManager.NameNotFoundException()).when(mPackageManager)
5832                 .getApplicationInfo(TEST_PACKAGE_NAME, 0);
5833         // Send the broadcast
5834         Intent intent = new Intent(Intent.ACTION_PACKAGE_FULLY_REMOVED);
5835         intent.putExtra(Intent.EXTRA_UID, uid);
5836         intent.setData(Uri.fromParts("package", packageName, ""));
5837         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
5838         mLooper.dispatchAll();
5839 
5840         ArgumentCaptor<ApplicationInfo> aiCaptor = ArgumentCaptor.forClass(ApplicationInfo.class);
5841         verify(mWifiConfigManager).removeNetworksForApp(aiCaptor.capture());
5842         assertNotNull(aiCaptor.getValue());
5843         assertEquals(uid, aiCaptor.getValue().uid);
5844         assertEquals(packageName, aiCaptor.getValue().packageName);
5845 
5846         verify(mScanRequestProxy).clearScanRequestTimestampsForApp(packageName, uid);
5847         verify(mWifiNetworkSuggestionsManager).removeApp(packageName);
5848         verify(mWifiNetworkFactory).removeApp(packageName);
5849         verify(mPasspointManager).removePasspointProviderWithPackage(packageName);
5850     }
5851 
5852     @Test
testPackageRemovedBroadcastHandling()5853     public void testPackageRemovedBroadcastHandling() throws Exception {
5854         mWifiServiceImpl.checkAndStartWifi();
5855         mLooper.dispatchAll();
5856         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5857                 argThat((IntentFilter filter) ->
5858                         filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
5859                                 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED)
5860                                 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)),
5861                 isNull(),
5862                 any(Handler.class));
5863         int uid = TEST_UID;
5864         String packageName = TEST_PACKAGE_NAME;
5865         // Send the broadcast
5866         Intent intent = new Intent(Intent.ACTION_PACKAGE_REMOVED);
5867         intent.putExtra(Intent.EXTRA_UID, uid);
5868         intent.setData(Uri.fromParts("package", packageName, ""));
5869         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
5870         mLooper.dispatchAll();
5871 
5872         ArgumentCaptor<ApplicationInfo> aiCaptor = ArgumentCaptor.forClass(ApplicationInfo.class);
5873         verify(mWifiConfigManager).removeNetworksForApp(aiCaptor.capture());
5874         assertNotNull(aiCaptor.getValue());
5875         assertEquals(uid, aiCaptor.getValue().uid);
5876         assertEquals(packageName, aiCaptor.getValue().packageName);
5877 
5878         verify(mScanRequestProxy).clearScanRequestTimestampsForApp(packageName, uid);
5879         verify(mWifiNetworkSuggestionsManager).removeApp(packageName);
5880         verify(mWifiNetworkFactory).removeApp(packageName);
5881         verify(mPasspointManager).removePasspointProviderWithPackage(packageName);
5882     }
5883 
5884     @Test
testPackageDisableBroadcastHandling()5885     public void testPackageDisableBroadcastHandling() throws Exception {
5886         mWifiServiceImpl.checkAndStartWifi();
5887         mLooper.dispatchAll();
5888         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5889                 argThat((IntentFilter filter) ->
5890                         filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)
5891                                 && filter.hasAction(Intent.ACTION_PACKAGE_REMOVED)
5892                                 && filter.hasAction(Intent.ACTION_PACKAGE_CHANGED)),
5893                 isNull(),
5894                 any(Handler.class));
5895         int uid = TEST_UID;
5896         String packageName = TEST_PACKAGE_NAME;
5897         mPackageInfo.applicationInfo = mApplicationInfo;
5898         mApplicationInfo.enabled = false;
5899         // Send the broadcast
5900         Intent intent = new Intent(Intent.ACTION_PACKAGE_CHANGED);
5901         intent.putExtra(Intent.EXTRA_UID, uid);
5902         intent.setData(Uri.fromParts("package", packageName, ""));
5903         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
5904         mLooper.dispatchAll();
5905 
5906         ArgumentCaptor<ApplicationInfo> aiCaptor = ArgumentCaptor.forClass(ApplicationInfo.class);
5907         verify(mWifiConfigManager).removeNetworksForApp(aiCaptor.capture());
5908         assertNotNull(aiCaptor.getValue());
5909         assertEquals(uid, aiCaptor.getValue().uid);
5910         assertEquals(packageName, aiCaptor.getValue().packageName);
5911 
5912         verify(mScanRequestProxy).clearScanRequestTimestampsForApp(packageName, uid);
5913         verify(mWifiNetworkSuggestionsManager).removeApp(packageName);
5914         verify(mWifiNetworkFactory).removeApp(packageName);
5915         verify(mPasspointManager).removePasspointProviderWithPackage(packageName);
5916     }
5917 
5918     @Test
testPackageRemovedBroadcastHandlingWithNoUid()5919     public void testPackageRemovedBroadcastHandlingWithNoUid() {
5920         mWifiServiceImpl.checkAndStartWifi();
5921         mLooper.dispatchAll();
5922         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5923                 argThat((IntentFilter filter) ->
5924                         filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)),
5925                 isNull(),
5926                 any(Handler.class));
5927 
5928         String packageName = TEST_PACKAGE_NAME;
5929         // Send the broadcast
5930         Intent intent = new Intent(Intent.ACTION_PACKAGE_REMOVED);
5931         intent.setData(Uri.fromParts("package", packageName, ""));
5932         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
5933 
5934         verify(mWifiConfigManager, never()).removeNetworksForApp(any());
5935 
5936         mLooper.dispatchAll();
5937         verify(mScanRequestProxy, never()).clearScanRequestTimestampsForApp(anyString(), anyInt());
5938         verify(mWifiNetworkSuggestionsManager, never()).removeApp(anyString());
5939         verify(mWifiNetworkFactory, never()).removeApp(anyString());
5940         verify(mPasspointManager, never()).removePasspointProviderWithPackage(anyString());
5941     }
5942 
5943     @Test
testPackageRemovedBroadcastHandlingWithNoPackageName()5944     public void testPackageRemovedBroadcastHandlingWithNoPackageName() {
5945         mWifiServiceImpl.checkAndStartWifi();
5946         mLooper.dispatchAll();
5947         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5948                 argThat((IntentFilter filter) ->
5949                         filter.hasAction(Intent.ACTION_PACKAGE_FULLY_REMOVED)),
5950                 isNull(),
5951                 any(Handler.class));
5952 
5953         int uid = TEST_UID;
5954         // Send the broadcast
5955         Intent intent = new Intent(Intent.ACTION_PACKAGE_FULLY_REMOVED);
5956         intent.putExtra(Intent.EXTRA_UID, uid);
5957         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
5958 
5959         verify(mWifiConfigManager, never()).removeNetworksForApp(any());
5960 
5961         mLooper.dispatchAll();
5962         verify(mScanRequestProxy, never()).clearScanRequestTimestampsForApp(anyString(), anyInt());
5963         verify(mWifiNetworkSuggestionsManager, never()).removeApp(anyString());
5964         verify(mWifiNetworkFactory, never()).removeApp(anyString());
5965         verify(mPasspointManager, never()).removePasspointProviderWithPackage(anyString());
5966     }
5967 
5968     @Test
testUserRemovedBroadcastHandling()5969     public void testUserRemovedBroadcastHandling() {
5970         mWifiServiceImpl.checkAndStartWifi();
5971         mWifiServiceImpl.handleBootCompleted();
5972         mLooper.dispatchAll();
5973         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5974                 argThat((IntentFilter filter) ->
5975                         filter.hasAction(Intent.ACTION_USER_REMOVED)),
5976                 isNull(),
5977                 any(Handler.class));
5978 
5979         UserHandle userHandle = UserHandle.of(TEST_USER_HANDLE);
5980         // Send the broadcast
5981         Intent intent = new Intent(Intent.ACTION_USER_REMOVED);
5982         intent.putExtra(Intent.EXTRA_USER, userHandle);
5983         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
5984         mLooper.dispatchAll();
5985 
5986         verify(mWifiConfigManager).removeNetworksForUser(userHandle.getIdentifier());
5987     }
5988 
5989     @Test
testBluetoothBroadcastHandling()5990     public void testBluetoothBroadcastHandling() {
5991         mWifiServiceImpl.checkAndStartWifi();
5992         mWifiServiceImpl.handleBootCompleted();
5993         mLooper.dispatchAll();
5994         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
5995                 argThat((IntentFilter filter) ->
5996                         filter.hasAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED)
5997                                 && filter.hasAction(BluetoothAdapter.ACTION_STATE_CHANGED)),
5998                 isNull(),
5999                 any(Handler.class));
6000 
6001         {
6002             Intent intent = new Intent(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
6003             intent.putExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
6004                     BluetoothAdapter.STATE_DISCONNECTED);
6005             mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6006             mLooper.dispatchAll();
6007 
6008             verify(mWifiGlobals).setBluetoothConnected(false);
6009             for (ClientModeManager cmm : mClientModeManagers) {
6010                 verify(cmm).onBluetoothConnectionStateChanged();
6011             }
6012         }
6013 
6014         {
6015             Intent intent = new Intent(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
6016             intent.putExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE,
6017                     BluetoothAdapter.STATE_CONNECTED);
6018             mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6019             mLooper.dispatchAll();
6020 
6021             verify(mWifiGlobals).setBluetoothConnected(true);
6022             for (ClientModeManager cmm : mClientModeManagers) {
6023                 verify(cmm, times(2)).onBluetoothConnectionStateChanged();
6024             }
6025         }
6026 
6027         {
6028             Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
6029             intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
6030             mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6031             mLooper.dispatchAll();
6032 
6033             verify(mWifiGlobals).setBluetoothEnabled(false);
6034             for (ClientModeManager cmm : mClientModeManagers) {
6035                 verify(cmm, times(3)).onBluetoothConnectionStateChanged();
6036             }
6037         }
6038 
6039         {
6040             Intent intent = new Intent(BluetoothAdapter.ACTION_STATE_CHANGED);
6041             intent.putExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_ON);
6042             mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6043             mLooper.dispatchAll();
6044 
6045             verify(mWifiGlobals).setBluetoothEnabled(true);
6046             for (ClientModeManager cmm : mClientModeManagers) {
6047                 verify(cmm, times(4)).onBluetoothConnectionStateChanged();
6048             }
6049         }
6050     }
6051 
6052     @Test
testUserRemovedBroadcastHandlingWithWrongIntentAction()6053     public void testUserRemovedBroadcastHandlingWithWrongIntentAction() {
6054         mWifiServiceImpl.checkAndStartWifi();
6055         mWifiServiceImpl.handleBootCompleted();
6056         mLooper.dispatchAll();
6057         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
6058                 argThat((IntentFilter filter) ->
6059                         filter.hasAction(Intent.ACTION_USER_REMOVED)),
6060                 isNull(),
6061                 any(Handler.class));
6062 
6063         UserHandle userHandle = UserHandle.of(TEST_USER_HANDLE);
6064         // Send the broadcast with wrong action
6065         Intent intent = new Intent(Intent.ACTION_USER_FOREGROUND);
6066         intent.putExtra(Intent.EXTRA_USER, userHandle);
6067         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6068 
6069         verify(mWifiConfigManager, never()).removeNetworksForUser(anyInt());
6070     }
6071 
6072     private class IdleModeIntentMatcher implements ArgumentMatcher<IntentFilter> {
6073         @Override
matches(IntentFilter filter)6074         public boolean matches(IntentFilter filter) {
6075             return filter.hasAction(PowerManager.ACTION_DEVICE_IDLE_MODE_CHANGED);
6076         }
6077     }
6078 
6079     /**
6080      * Verifies that enforceChangePermission(String package) is called and the caller doesn't
6081      * have NETWORK_SETTINGS permission
6082      */
verifyCheckChangePermission(String callingPackageName)6083     private void verifyCheckChangePermission(String callingPackageName) {
6084         verify(mContext, atLeastOnce())
6085                 .checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6086                         anyInt(), anyInt());
6087         verify(mContext, atLeastOnce()).enforceCallingOrSelfPermission(
6088                 android.Manifest.permission.CHANGE_WIFI_STATE, "WifiService");
6089         verify(mAppOpsManager, atLeastOnce()).noteOp(
6090                 AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), callingPackageName);
6091     }
6092 
createValidWifiApConfiguration()6093     private WifiConfiguration createValidWifiApConfiguration() {
6094         WifiConfiguration apConfig = new WifiConfiguration();
6095         apConfig.SSID = "TestAp";
6096         apConfig.preSharedKey = "thisIsABadPassword";
6097         apConfig.allowedKeyManagement.set(KeyMgmt.WPA2_PSK);
6098         apConfig.apBand = WifiConfiguration.AP_BAND_2GHZ;
6099 
6100         return apConfig;
6101     }
6102 
createValidSoftApConfiguration()6103     private SoftApConfiguration createValidSoftApConfiguration() {
6104         return new SoftApConfiguration.Builder()
6105                 .setSsid("TestAp")
6106                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
6107                 .setBand(SoftApConfiguration.BAND_2GHZ)
6108                 .build();
6109     }
6110 
6111     /**
6112      * Verifies that sim state change does not set or reset the country code
6113      */
6114     @Test
testSimStateChangeDoesNotResetCountryCode()6115     public void testSimStateChangeDoesNotResetCountryCode() {
6116         mWifiServiceImpl.checkAndStartWifi();
6117         mLooper.dispatchAll();
6118         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
6119                 (IntentFilter) argThat((IntentFilter filter) ->
6120                         filter.hasAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED)),
6121                 isNull(),
6122                 any(Handler.class));
6123 
6124         int userHandle = TEST_USER_HANDLE;
6125         // Send the broadcast
6126         Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED);
6127         intent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
6128         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6129         verify(mWifiCountryCode, never()).setTelephonyCountryCodeAndUpdate(any());
6130     }
6131 
6132     /**
6133      * Verifies that sim state change does not set or reset the country code
6134      */
6135     @Test
testSimStateChangeDoesNotResetCountryCodeForRebroadcastedIntent()6136     public void testSimStateChangeDoesNotResetCountryCodeForRebroadcastedIntent() {
6137         mWifiServiceImpl.checkAndStartWifi();
6138         mLooper.dispatchAll();
6139         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
6140                 (IntentFilter) argThat((IntentFilter filter) ->
6141                         filter.hasAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED)),
6142                 isNull(),
6143                 any(Handler.class));
6144 
6145         int userHandle = TEST_USER_HANDLE;
6146         // Send the broadcast
6147         Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED);
6148         intent.putExtra(Intent.EXTRA_USER_HANDLE, userHandle);
6149         intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, Intent.SIM_STATE_ABSENT);
6150         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6151         verify(mWifiCountryCode, never()).setTelephonyCountryCodeAndUpdate(any());
6152     }
6153 
6154     /**
6155      * Verify removing sim will also remove an ephemeral Passpoint Provider. And reset carrier
6156      * privileged suggestor apps.
6157      */
6158     @Test
testResetSimNetworkWhenRemovingSim()6159     public void testResetSimNetworkWhenRemovingSim() throws Exception {
6160         mWifiServiceImpl.checkAndStartWifi();
6161         mLooper.dispatchAll();
6162         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
6163                 argThat((IntentFilter filter) ->
6164                         filter.hasAction(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED)),
6165                 isNull(),
6166                 any(Handler.class));
6167 
6168         Intent intent = new Intent(TelephonyManager.ACTION_SIM_CARD_STATE_CHANGED);
6169         intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, TelephonyManager.SIM_STATE_ABSENT);
6170         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6171         mLooper.dispatchAll();
6172 
6173         verify(mWifiConfigManager).resetSimNetworks();
6174         verify(mWifiConfigManager).stopRestrictingAutoJoinToSubscriptionId();
6175         verify(mSimRequiredNotifier, never()).dismissSimRequiredNotification();
6176         verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps();
6177         verify(mWifiConfigManager, never()).removeAllEphemeralOrPasspointConfiguredNetworks();
6178         verify(mWifiNetworkSuggestionsManager).resetSimNetworkSuggestions();
6179         verify(mPasspointManager).resetSimPasspointNetwork();
6180     }
6181 
6182     /**
6183      * Verify inserting sim will reset carrier privileged suggestor apps.
6184      * and remove any previous notifications due to sim removal
6185      */
6186     @Test
testResetCarrierPrivilegedAppsWhenInsertingSim()6187     public void testResetCarrierPrivilegedAppsWhenInsertingSim() throws Exception {
6188         mWifiServiceImpl.checkAndStartWifi();
6189         mLooper.dispatchAll();
6190         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
6191                 argThat((IntentFilter filter) ->
6192                         filter.hasAction(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED)),
6193                 isNull(),
6194                 any(Handler.class));
6195 
6196         Intent intent = new Intent(TelephonyManager.ACTION_SIM_APPLICATION_STATE_CHANGED);
6197         intent.putExtra(TelephonyManager.EXTRA_SIM_STATE, TelephonyManager.SIM_STATE_LOADED);
6198         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6199         mLooper.dispatchAll();
6200 
6201         verify(mWifiConfigManager, never()).resetSimNetworks();
6202         verify(mPasspointManager, never()).resetSimPasspointNetwork();
6203         verify(mWifiNetworkSuggestionsManager, never()).resetSimNetworkSuggestions();
6204         verify(mWifiConfigManager, never()).stopRestrictingAutoJoinToSubscriptionId();
6205         verify(mSimRequiredNotifier).dismissSimRequiredNotification();
6206         verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps();
6207         verify(mWifiConfigManager, never()).removeAllEphemeralOrPasspointConfiguredNetworks();
6208         verify(mWifiConfigManager).enableTemporaryDisabledNetworks();
6209         verify(mWifiConnectivityManager).forceConnectivityScan(any());
6210     }
6211 
6212     @Test
testResetSimNetworkWhenDefaultDataSimChanged()6213     public void testResetSimNetworkWhenDefaultDataSimChanged() throws Exception {
6214         mWifiServiceImpl.checkAndStartWifi();
6215         mLooper.dispatchAll();
6216         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
6217                 argThat((IntentFilter filter) ->
6218                         filter.hasAction(
6219                                 TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED)),
6220                 isNull(),
6221                 any(Handler.class));
6222 
6223         Intent intent = new Intent(TelephonyManager.ACTION_DEFAULT_DATA_SUBSCRIPTION_CHANGED);
6224         intent.putExtra("subscription", 1);
6225         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
6226         mLooper.dispatchAll();
6227 
6228         verify(mWifiConfigManager).resetSimNetworks();
6229         verify(mWifiConfigManager).stopRestrictingAutoJoinToSubscriptionId();
6230         verify(mSimRequiredNotifier, never()).dismissSimRequiredNotification();
6231         verify(mWifiNetworkSuggestionsManager).updateCarrierPrivilegedApps();
6232         verify(mWifiConfigManager).removeEphemeralCarrierNetworks(anySet());
6233         verify(mWifiNetworkSuggestionsManager).resetSimNetworkSuggestions();
6234         verify(mPasspointManager).resetSimPasspointNetwork();
6235         verify(mWifiDataStall).resetPhoneStateListener();
6236     }
6237 
6238     /**
6239      * Verify that a call to registerTrafficStateCallback throws a SecurityException if the caller
6240      * does not have NETWORK_SETTINGS permission.
6241      */
6242     @Test
registerTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions()6243     public void registerTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions() {
6244         doThrow(new SecurityException()).when(mContext)
6245                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6246                         eq("WifiService"));
6247         try {
6248             mWifiServiceImpl.registerTrafficStateCallback(mTrafficStateCallback);
6249             fail("expected SecurityException");
6250         } catch (SecurityException expected) {
6251         }
6252     }
6253 
6254     /**
6255      * Verify that a call to registerTrafficStateCallback throws an IllegalArgumentException if the
6256      * parameters are not provided.
6257      */
6258     @Test
registerTrafficStateCallbackThrowsIllegalArgumentExceptionOnInvalidArguments()6259     public void registerTrafficStateCallbackThrowsIllegalArgumentExceptionOnInvalidArguments() {
6260         try {
6261             mWifiServiceImpl.registerTrafficStateCallback(null);
6262             fail("expected IllegalArgumentException");
6263         } catch (IllegalArgumentException expected) {
6264         }
6265     }
6266 
6267     /**
6268      * Verify that a call to unregisterTrafficStateCallback throws a SecurityException if the caller
6269      * does not have NETWORK_SETTINGS permission.
6270      */
6271     @Test
unregisterTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions()6272     public void unregisterTrafficStateCallbackThrowsSecurityExceptionOnMissingPermissions() {
6273         doThrow(new SecurityException()).when(mContext)
6274                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6275                         eq("WifiService"));
6276         try {
6277             mWifiServiceImpl.unregisterTrafficStateCallback(mTrafficStateCallback);
6278             fail("expected SecurityException");
6279         } catch (SecurityException expected) {
6280         }
6281     }
6282 
6283     /**
6284      * Verify that registerTrafficStateCallback adds callback to {@link WifiTrafficPoller}.
6285      */
6286     @Test
registerTrafficStateCallbackAndVerify()6287     public void registerTrafficStateCallbackAndVerify() throws Exception {
6288         mWifiServiceImpl.registerTrafficStateCallback(mTrafficStateCallback);
6289         mLooper.dispatchAll();
6290         verify(mWifiTrafficPoller).addCallback(mTrafficStateCallback);
6291     }
6292 
6293     /**
6294      * Verify that unregisterTrafficStateCallback removes callback from {@link WifiTrafficPoller}.
6295      */
6296     @Test
unregisterTrafficStateCallbackAndVerify()6297     public void unregisterTrafficStateCallbackAndVerify() throws Exception {
6298         mWifiServiceImpl.unregisterTrafficStateCallback(mTrafficStateCallback);
6299         mLooper.dispatchAll();
6300         verify(mWifiTrafficPoller).removeCallback(mTrafficStateCallback);
6301     }
6302 
6303     /**
6304      * Verify that a call to registerNetworkRequestMatchCallback throws a SecurityException if the
6305      * caller does not have NETWORK_SETTINGS permission.
6306      */
6307     @Test
registerNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions()6308     public void registerNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions() {
6309         doThrow(new SecurityException()).when(mContext)
6310                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6311                         eq("WifiService"));
6312         try {
6313             mWifiServiceImpl.registerNetworkRequestMatchCallback(mNetworkRequestMatchCallback);
6314             fail("expected SecurityException");
6315         } catch (SecurityException expected) {
6316         }
6317     }
6318 
6319     /**
6320      * Verify that a call to registerNetworkRequestMatchCallback throws an IllegalArgumentException
6321      * if the parameters are not provided.
6322      */
6323     @Test
6324     public void
registerNetworkRequestMatchCallbackThrowsIllegalArgumentExceptionOnInvalidArguments()6325             registerNetworkRequestMatchCallbackThrowsIllegalArgumentExceptionOnInvalidArguments() {
6326         try {
6327             mWifiServiceImpl.registerNetworkRequestMatchCallback(null);
6328             fail("expected IllegalArgumentException");
6329         } catch (IllegalArgumentException expected) {
6330         }
6331     }
6332 
6333     /**
6334      * Verify that a call to unregisterNetworkRequestMatchCallback throws a SecurityException if the
6335      * caller does not have NETWORK_SETTINGS permission.
6336      */
6337     @Test
unregisterNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions()6338     public void unregisterNetworkRequestMatchCallbackThrowsSecurityExceptionOnMissingPermissions() {
6339         doThrow(new SecurityException()).when(mContext)
6340                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6341                         eq("WifiService"));
6342         try {
6343             mWifiServiceImpl.unregisterNetworkRequestMatchCallback(mNetworkRequestMatchCallback);
6344             fail("expected SecurityException");
6345         } catch (SecurityException expected) {
6346         }
6347     }
6348 
6349     /**
6350      * Verify that registerNetworkRequestMatchCallback adds callback to
6351      * {@link ClientModeManager}.
6352      */
6353     @Test
registerNetworkRequestMatchCallbackAndVerify()6354     public void registerNetworkRequestMatchCallbackAndVerify() throws Exception {
6355         mWifiServiceImpl.registerNetworkRequestMatchCallback(mNetworkRequestMatchCallback);
6356         mLooper.dispatchAll();
6357         verify(mWifiNetworkFactory).addCallback(mNetworkRequestMatchCallback);
6358     }
6359 
6360     /**
6361      * Verify that unregisterNetworkRequestMatchCallback removes callback from
6362      * {@link ClientModeManager}.
6363      */
6364     @Test
unregisterNetworkRequestMatchCallbackAndVerify()6365     public void unregisterNetworkRequestMatchCallbackAndVerify() throws Exception {
6366         mWifiServiceImpl.unregisterNetworkRequestMatchCallback(mNetworkRequestMatchCallback);
6367         mLooper.dispatchAll();
6368         verify(mWifiNetworkFactory).removeCallback(mNetworkRequestMatchCallback);
6369     }
6370 
6371     /**
6372      * Verify that Wifi configuration and Passpoint configuration are removed in factoryReset.
6373      */
6374     @Test
testFactoryReset()6375     public void testFactoryReset() throws Exception {
6376         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6377                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
6378         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
6379         final String fqdn = "example.com";
6380         WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
6381         openNetwork.networkId = TEST_NETWORK_ID;
6382         WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork(
6383                 WifiEnterpriseConfig.Eap.TLS, WifiEnterpriseConfig.Phase2.NONE);
6384         eapNetwork.networkId = TEST_NETWORK_ID + 1;
6385         PasspointConfiguration config = new PasspointConfiguration();
6386         HomeSp homeSp = new HomeSp();
6387         homeSp.setFqdn(fqdn);
6388         config.setHomeSp(homeSp);
6389         Credential credential = new Credential();
6390         credential.setRealm("example.com");
6391         config.setCredential(credential);
6392 
6393         when(mWifiConfigManager.getSavedNetworks(anyInt()))
6394                 .thenReturn(Arrays.asList(openNetwork, eapNetwork));
6395         when(mPasspointManager.getProviderConfigs(anyInt(), anyBoolean()))
6396                 .thenReturn(Arrays.asList(config));
6397 
6398         mLooper.startAutoDispatch();
6399         mWifiServiceImpl.factoryReset(TEST_PACKAGE_NAME);
6400         mLooper.stopAutoDispatchAndIgnoreExceptions();
6401 
6402         // Let the final post inside the |factoryReset| method run to completion.
6403         mLooper.dispatchAll();
6404 
6405         verify(mWifiApConfigStore).setApConfiguration(null);
6406         verify(mWifiConfigManager).removeNetwork(
6407                 openNetwork.networkId, Binder.getCallingUid(), TEST_PACKAGE_NAME);
6408         verify(mWifiConfigManager).removeNetwork(
6409                 eapNetwork.networkId, Binder.getCallingUid(), TEST_PACKAGE_NAME);
6410         verify(mWifiKeyStore).removeKeys(eapNetwork.enterpriseConfig, true);
6411         verify(mPasspointManager).removeProvider(anyInt(), anyBoolean(), eq(config.getUniqueId()),
6412                 isNull());
6413         verify(mPasspointManager).clearAnqpRequestsAndFlushCache();
6414         verify(mWifiConfigManager).clearUserTemporarilyDisabledList();
6415         verify(mWifiConfigManager).removeAllEphemeralOrPasspointConfiguredNetworks();
6416         verify(mWifiNetworkFactory).clear();
6417         verify(mWifiNetworkSuggestionsManager).clear();
6418         verify(mWifiScoreCard).clear();
6419         verify(mWifiHealthMonitor).clear();
6420         verify(mPasspointManager).getProviderConfigs(anyInt(), anyBoolean());
6421     }
6422 
6423     /**
6424      * Verify that a call to factoryReset throws a SecurityException if the caller does not have
6425      * the NETWORK_SETTINGS permission.
6426      */
6427     @Test
testFactoryResetWithoutNetworkSettingsPermission()6428     public void testFactoryResetWithoutNetworkSettingsPermission() throws Exception {
6429         doThrow(new SecurityException()).when(mContext)
6430                 .enforceCallingOrSelfPermission(eq(Manifest.permission.NETWORK_SETTINGS),
6431                         eq("WifiService"));
6432         try {
6433             mWifiServiceImpl.factoryReset(TEST_PACKAGE_NAME);
6434             fail();
6435         } catch (SecurityException e) {
6436         }
6437         verify(mWifiConfigManager, never()).getSavedNetworks(anyInt());
6438         verify(mPasspointManager, never()).getProviderConfigs(anyInt(), anyBoolean());
6439     }
6440 
6441     /**
6442      * Verify that add or update networks is not allowed for apps targeting Q SDK.
6443      */
6444     @Test
testAddOrUpdateNetworkIsNotAllowedForAppsTargetingQSdk()6445     public void testAddOrUpdateNetworkIsNotAllowedForAppsTargetingQSdk() throws Exception {
6446         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6447                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6448         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6449                 new NetworkUpdateResult(0));
6450 
6451         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6452         mLooper.startAutoDispatch();
6453         assertEquals(-1,
6454                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6455         mLooper.stopAutoDispatchAndIgnoreExceptions();
6456 
6457         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6458         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6459         verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls();
6460     }
6461 
6462     /**
6463      * Verify that add or update networks is allowed for apps targeting below Q SDK.
6464      */
6465     @Test
testAddOrUpdateNetworkIsAllowedForAppsTargetingBelowQSdk()6466     public void testAddOrUpdateNetworkIsAllowedForAppsTargetingBelowQSdk() throws Exception {
6467         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6468                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6469         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6470                 new NetworkUpdateResult(0));
6471         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
6472                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
6473 
6474         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6475         mLooper.startAutoDispatch();
6476         assertEquals(0,
6477                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6478         mLooper.stopAutoDispatchAndIgnoreExceptions();
6479 
6480         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6481         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6482         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6483     }
6484 
6485     /**
6486      * Verify that add or update networks is not allowed for apps targeting below Q SDK
6487      * when DISALLOW_ADD_WIFI_CONFIG user restriction is set.
6488      */
6489     @Test
testAddOrUpdateNetworkIsNotAllowedForAppsTargetingBelowQSdkWithUserRestriction()6490     public void testAddOrUpdateNetworkIsNotAllowedForAppsTargetingBelowQSdkWithUserRestriction()
6491             throws Exception {
6492         assumeTrue(SdkLevel.isAtLeastT());
6493         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6494                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6495         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6496                 new NetworkUpdateResult(0));
6497         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
6498                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
6499         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
6500                 any())).thenReturn(true);
6501 
6502         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6503         mLooper.startAutoDispatch();
6504         assertEquals(-1,
6505                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6506         mLooper.stopAutoDispatchAndIgnoreExceptions();
6507 
6508         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6509         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6510         verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls();
6511     }
6512 
6513     /**
6514      * Verify that add or update networks is not allowed for camera app when
6515      * DISALLOW_CONFIG_WIFI user restriction is set.
6516      */
6517     @Test
testAddOrUpdateNetworkIsNotAllowedForCameraDisallowConfigWifi()6518     public void testAddOrUpdateNetworkIsNotAllowedForCameraDisallowConfigWifi() throws Exception {
6519         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6520                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6521         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
6522         when(mWifiPermissionsUtil.checkCameraPermission(Binder.getCallingUid())).thenReturn(true);
6523         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6524                 .thenReturn(false);
6525         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6526                 new NetworkUpdateResult(0));
6527         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_CONFIG_WIFI),
6528                 any())).thenReturn(true);
6529 
6530         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6531         mLooper.startAutoDispatch();
6532         assertEquals(-1,
6533                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6534         mLooper.stopAutoDispatchAndIgnoreExceptions();
6535 
6536         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6537         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6538         verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls();
6539     }
6540 
6541     /**
6542      * Verify that add or update networks is not allowed for camera app when
6543      * DISALLOW_ADD_WIFI_CONFIG user restriction is set.
6544      */
6545     @Test
testAddOrUpdateNetworkIsNotAllowedForCameraDisallowAddWifiConfig()6546     public void testAddOrUpdateNetworkIsNotAllowedForCameraDisallowAddWifiConfig()
6547             throws Exception {
6548         assumeTrue(SdkLevel.isAtLeastT());
6549         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6550                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6551         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
6552         when(mWifiPermissionsUtil.checkCameraPermission(Binder.getCallingUid())).thenReturn(true);
6553         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6554                 .thenReturn(false);
6555         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6556                 new NetworkUpdateResult(0));
6557         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
6558                 any())).thenReturn(true);
6559 
6560         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6561         mLooper.startAutoDispatch();
6562         assertEquals(-1,
6563                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6564         mLooper.stopAutoDispatchAndIgnoreExceptions();
6565 
6566         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6567         verify(mWifiConfigManager, never()).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6568         verify(mWifiMetrics, never()).incrementNumAddOrUpdateNetworkCalls();
6569     }
6570 
6571     /**
6572      * Verify that add or update networks is allowed for settings app.
6573      */
6574     @Test
testAddOrUpdateNetworkIsAllowedForSettingsApp()6575     public void testAddOrUpdateNetworkIsAllowedForSettingsApp() throws Exception {
6576         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6577                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
6578         mApplicationInfo.targetSdkVersion = Build.VERSION_CODES.P;
6579         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6580                 new NetworkUpdateResult(0));
6581 
6582         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6583         mLooper.startAutoDispatch();
6584         assertEquals(0,
6585                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6586         mLooper.stopAutoDispatchAndIgnoreExceptions();
6587 
6588         // Ensure that we don't check for change permission.
6589         verify(mContext, never()).enforceCallingOrSelfPermission(
6590                 android.Manifest.permission.CHANGE_WIFI_STATE, "WifiService");
6591         verify(mAppOpsManager, never()).noteOp(
6592                 AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6593         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6594         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6595     }
6596 
6597     /**
6598      * Verify that add or update networks is allowed for system apps.
6599      */
6600     @Test
testAddOrUpdateNetworkIsAllowedForSystemApp()6601     public void testAddOrUpdateNetworkIsAllowedForSystemApp() throws Exception {
6602         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6603                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6604         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
6605         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6606                 new NetworkUpdateResult(0));
6607 
6608         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6609         mLooper.startAutoDispatch();
6610         assertEquals(0,
6611                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6612         mLooper.stopAutoDispatchAndIgnoreExceptions();
6613 
6614         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6615         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6616         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6617     }
6618 
6619     /**
6620      * Verify that add or update networks is allowed for apps holding system alert permission.
6621      */
6622     @Test
testAddOrUpdateNetworkIsAllowedForAppsWithSystemAlertPermission()6623     public void testAddOrUpdateNetworkIsAllowedForAppsWithSystemAlertPermission() throws Exception {
6624         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6625                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6626         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6627                 new NetworkUpdateResult(0));
6628 
6629         // Verify caller fails to add network as Guest user.
6630         when(mWifiPermissionsUtil.checkSystemAlertWindowPermission(
6631                 Process.myUid(), TEST_PACKAGE_NAME)).thenReturn(true);
6632         when(mWifiPermissionsUtil.isGuestUser()).thenReturn(true);
6633         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6634         mLooper.startAutoDispatch();
6635         assertEquals(-1,
6636                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6637 
6638         // Verify caller successfully add network when not a Guest user.
6639         when(mWifiPermissionsUtil.isGuestUser()).thenReturn(false);
6640         assertEquals(0,
6641                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6642         mLooper.stopAutoDispatchAndIgnoreExceptions();
6643 
6644         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6645         verify(mWifiPermissionsUtil, times(2))
6646                 .checkSystemAlertWindowPermission(anyInt(), anyString());
6647         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6648         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6649     }
6650 
6651     /**
6652      * Verify that add or update networks is allowed for DeviceOwner app.
6653      */
6654     @Test
testAddOrUpdateNetworkIsAllowedForDOApp()6655     public void testAddOrUpdateNetworkIsAllowedForDOApp() throws Exception {
6656         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6657                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6658         when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6659                 .thenReturn(true);
6660         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6661                 new NetworkUpdateResult(0));
6662         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6663                 .thenReturn(true);
6664 
6665         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6666         mLooper.startAutoDispatch();
6667         assertEquals(0,
6668                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6669         mLooper.stopAutoDispatchAndIgnoreExceptions();
6670 
6671         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6672         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6673         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6674     }
6675 
6676     /**
6677      * Verify that add or update networks is allowed for ProfileOwner app.
6678      */
6679     @Test
testAddOrUpdateNetworkIsAllowedForPOApp()6680     public void testAddOrUpdateNetworkIsAllowedForPOApp() throws Exception {
6681         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6682                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6683         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6684                 .thenReturn(true);
6685         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6686                 new NetworkUpdateResult(0));
6687         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6688                 .thenReturn(true);
6689 
6690         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6691         mLooper.startAutoDispatch();
6692         assertEquals(0,
6693                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6694         mLooper.stopAutoDispatchAndIgnoreExceptions();
6695 
6696         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6697         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6698         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6699     }
6700 
6701     /**
6702      * Verify that add or update networks is allowed for an admin app.
6703      */
6704     @Test
testAddOrUpdateNetworkIsAllowedForAdminApp()6705     public void testAddOrUpdateNetworkIsAllowedForAdminApp() throws Exception {
6706         assumeTrue(SdkLevel.isAtLeastT());
6707         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6708                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6709         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6710                 .thenReturn(true);
6711         when(mWifiConfigManager.addOrUpdateNetwork(any(),  anyInt(), any(), eq(false))).thenReturn(
6712                 new NetworkUpdateResult(0));
6713 
6714         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6715         mLooper.startAutoDispatch();
6716         assertEquals(0,
6717                 mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution));
6718         mLooper.stopAutoDispatchAndIgnoreExceptions();
6719 
6720         verifyCheckChangePermission(TEST_PACKAGE_NAME);
6721         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6722         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6723     }
6724 
verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException()6725     private void verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException() {
6726         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6727         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false)))
6728                 .thenReturn(new NetworkUpdateResult(0));
6729         mLooper.startAutoDispatch();
6730         mWifiServiceImpl.addOrUpdateNetworkPrivileged(config, TEST_PACKAGE_NAME);
6731         mLooper.stopAutoDispatchAndIgnoreExceptions();
6732 
6733         verify(mWifiConfigManager).addOrUpdateNetwork(any(),  anyInt(), any(), eq(false));
6734         verify(mWifiMetrics).incrementNumAddOrUpdateNetworkCalls();
6735     }
6736 
6737     /**
6738      * Verify that addOrUpdateNetworkPrivileged throws a SecurityException if the calling app
6739      * has no permissions.
6740      */
6741     @Test
testAddOrUpdateNetworkPrivilegedNotAllowedForNormalApps()6742     public void testAddOrUpdateNetworkPrivilegedNotAllowedForNormalApps() throws Exception {
6743         try {
6744             WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6745             mWifiServiceImpl.addOrUpdateNetworkPrivileged(config, TEST_PACKAGE_NAME);
6746             fail("Expected SecurityException for apps without permission");
6747         } catch (SecurityException e) {
6748         }
6749     }
6750 
6751     /**
6752      * Verify that a privileged app with NETWORK_SETTINGS permission is allowed to call
6753      * addOrUpdateNetworkPrivileged.
6754      */
6755     @Test
testAddOrUpdateNetworkPrivilegedIsAllowedForPrivilegedApp()6756     public void testAddOrUpdateNetworkPrivilegedIsAllowedForPrivilegedApp() throws Exception {
6757         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6758                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
6759         verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException();
6760     }
6761 
6762     /**
6763      * Verify that a system app is allowed to call addOrUpdateNetworkPrivileged.
6764      */
6765     @Test
testAddOrUpdateNetworkPrivilegedIsAllowedForSystemApp()6766     public void testAddOrUpdateNetworkPrivilegedIsAllowedForSystemApp() throws Exception {
6767         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
6768         verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException();
6769     }
6770 
6771     /**
6772      * Verify that an admin app is allowed to call addOrUpdateNetworkPrivileged.
6773      */
6774     @Test
testAddOrUpdateNetworkPrivilegedIsAllowedForAdminApp()6775     public void testAddOrUpdateNetworkPrivilegedIsAllowedForAdminApp() throws Exception {
6776         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
6777                 .thenReturn(true);
6778         verifyAddOrUpdateNetworkPrivilegedDoesNotThrowException();
6779     }
6780 
6781     /**
6782      * Verify the proper status code is returned when addOrUpdateNetworkPrivileged failed due to
6783      * a failure in WifiConfigManager.addOrUpdateNetwork().
6784      */
6785     @Test
testAddOrUpdateNetworkInvalidConfiguration()6786     public void testAddOrUpdateNetworkInvalidConfiguration() throws Exception {
6787         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
6788         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false)))
6789                 .thenReturn(new NetworkUpdateResult(-1));
6790         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6791         mLooper.startAutoDispatch();
6792         WifiManager.AddNetworkResult result = mWifiServiceImpl.addOrUpdateNetworkPrivileged(
6793                 config, TEST_PACKAGE_NAME);
6794         mLooper.stopAutoDispatchAndIgnoreExceptions();
6795 
6796         assertEquals(WifiManager.AddNetworkResult.STATUS_ADD_WIFI_CONFIG_FAILURE,
6797                 result.statusCode);
6798         assertEquals(-1, result.networkId);
6799     }
6800 
6801     /**
6802      * Verify that enableNetwork is allowed for privileged Apps
6803      */
6804     @Test
testEnableNetworkWithDisableOthersAllowedForPrivilegedApps()6805     public void testEnableNetworkWithDisableOthersAllowedForPrivilegedApps() throws Exception {
6806         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
6807                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
6808         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6809                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6810 
6811         doAnswer(new AnswerWithArguments() {
6812             public void answer(NetworkUpdateResult result, ActionListenerWrapper callback,
6813                     int callingUid, String packageName) {
6814                 callback.sendSuccess(); // return success
6815             }
6816         }).when(mConnectHelper).connectToNetwork(
6817                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
6818 
6819         mLooper.startAutoDispatch();
6820         assertTrue(mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME));
6821         mLooper.stopAutoDispatch();
6822 
6823         verify(mConnectHelper).connectToNetwork(
6824                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
6825         verify(mWifiMetrics).incrementNumEnableNetworkCalls();
6826         verify(mLastCallerInfoManager).put(eq(WifiManager.API_ENABLE_NETWORK), anyInt(),
6827                 anyInt(), anyInt(), anyString(), eq(true));
6828     }
6829 
6830     /**
6831      * Verify that enableNetwork (with disableOthers=true) is allowed for Apps targeting a SDK
6832      * version less than Q
6833      */
6834     @Test
testEnabledNetworkWithDisableOthersAllowedForAppsTargetingBelowQSdk()6835     public void testEnabledNetworkWithDisableOthersAllowedForAppsTargetingBelowQSdk()
6836             throws Exception {
6837         mLooper.dispatchAll();
6838         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6839                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6840         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
6841                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
6842 
6843         doAnswer(new AnswerWithArguments() {
6844             public void answer(NetworkUpdateResult result, ActionListenerWrapper callback,
6845                     int callingUid, String packageName) {
6846                 callback.sendSuccess(); // return success
6847             }
6848         }).when(mConnectHelper).connectToNetwork(
6849                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
6850 
6851         mLooper.startAutoDispatch();
6852         assertTrue(mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME));
6853         mLooper.stopAutoDispatch();
6854 
6855         verify(mConnectHelper).connectToNetwork(
6856                 eq(new NetworkUpdateResult(TEST_NETWORK_ID)), any(), anyInt(), any());
6857         verify(mWifiMetrics).incrementNumEnableNetworkCalls();
6858     }
6859 
6860     /**
6861      * Verify that enableNetwork (with disableOthers=false) is allowed for Apps targeting a SDK
6862      * version less than Q
6863      */
6864     @Test
testEnabledNetworkWithoutDisableOthersAllowedForAppsTargetingBelowQSdk()6865     public void testEnabledNetworkWithoutDisableOthersAllowedForAppsTargetingBelowQSdk()
6866             throws Exception {
6867         mLooper.dispatchAll();
6868         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6869                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6870         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
6871                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
6872 
6873         when(mWifiConfigManager.enableNetwork(anyInt(), anyBoolean(), anyInt(), anyString()))
6874                 .thenReturn(true);
6875         mLooper.startAutoDispatch();
6876         assertTrue(mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, false, TEST_PACKAGE_NAME));
6877         mLooper.stopAutoDispatchAndIgnoreExceptions();
6878         verify(mWifiConfigManager).enableNetwork(eq(TEST_NETWORK_ID), eq(false),
6879                 eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME));
6880         verify(mWifiMetrics).incrementNumEnableNetworkCalls();
6881     }
6882 
6883     /**
6884      * Verify that enableNetwork is not allowed for Apps targeting Q SDK
6885      */
6886     @Test
testEnableNetworkNotAllowedForAppsTargetingQ()6887     public void testEnableNetworkNotAllowedForAppsTargetingQ() throws Exception {
6888         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6889                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6890 
6891         mLooper.startAutoDispatch();
6892         mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME);
6893         mLooper.stopAutoDispatchAndIgnoreExceptions();
6894 
6895         verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
6896         verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls();
6897     }
6898 
6899     /**
6900      * Verify that enableNetwork is not allowed for admin restricted network
6901      */
6902     @Test
testEnableNetworkNotAllowedForAdminRestrictedNetwork()6903     public void testEnableNetworkNotAllowedForAdminRestrictedNetwork() throws Exception {
6904         assumeTrue(SdkLevel.isAtLeastT());
6905         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6906                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6907         when(mWifiPermissionsUtil.isSystem(TEST_PACKAGE_NAME, Process.myUid())).thenReturn(true);
6908         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6909         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
6910         when(mWifiPermissionsUtil.isAdminRestrictedNetwork(config)).thenReturn(true);
6911 
6912         mLooper.startAutoDispatch();
6913         mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME);
6914         mLooper.stopAutoDispatchAndIgnoreExceptions();
6915 
6916         verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
6917         verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls();
6918     }
6919 
6920     /**
6921      * Verify that enableNetwork is not allowed for deprecated security type network
6922      */
6923     @Test
testEnableNetworkNotAllowedForDeprecatedSecurityTypeNetwork()6924     public void testEnableNetworkNotAllowedForDeprecatedSecurityTypeNetwork() throws Exception {
6925         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
6926                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
6927         when(mWifiPermissionsUtil.isSystem(TEST_PACKAGE_NAME, Process.myUid())).thenReturn(true);
6928         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork();
6929         when(mWifiConfigManager.getConfiguredNetwork(TEST_NETWORK_ID)).thenReturn(config);
6930         when(mWifiGlobals.isDeprecatedSecurityTypeNetwork(config)).thenReturn(true);
6931 
6932         mLooper.startAutoDispatch();
6933         mWifiServiceImpl.enableNetwork(TEST_NETWORK_ID, true, TEST_PACKAGE_NAME);
6934         mLooper.stopAutoDispatchAndIgnoreExceptions();
6935 
6936         verify(mConnectHelper, never()).connectToNetwork(any(), any(), anyInt(), any());
6937         verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls();
6938     }
6939 
6940     /**
6941      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network
6942      * suggestions.
6943      */
6944     @Test
testAddNetworkSuggestions()6945     public void testAddNetworkSuggestions() {
6946         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
6947                 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
6948         mLooper.startAutoDispatch();
6949         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
6950                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
6951                         TEST_FEATURE_ID));
6952         mLooper.stopAutoDispatchAndIgnoreExceptions();
6953 
6954         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
6955                 nullable(String.class))).thenReturn(
6956                 WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE);
6957         mLooper.startAutoDispatch();
6958         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_ADD_DUPLICATE,
6959                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
6960                         TEST_FEATURE_ID));
6961         mLooper.stopAutoDispatchAndIgnoreExceptions();
6962 
6963         verify(mWifiNetworkSuggestionsManager, times(2)).add(
6964                 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
6965     }
6966 
6967     /**
6968      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network
6969      * suggestions for carrier app when DISALLOW_ADD_WIFI_CONFIG user restriction is set.
6970      */
6971     @Test
testAddNetworkSuggestionsIsAllowedForCarrierAppWithUserRestriction()6972     public void testAddNetworkSuggestionsIsAllowedForCarrierAppWithUserRestriction() {
6973         assumeTrue(SdkLevel.isAtLeastT());
6974         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
6975                 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
6976         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
6977                 any())).thenReturn(true);
6978         when(mTelephonyManager.checkCarrierPrivilegesForPackageAnyPhone(anyString())).thenReturn(
6979                 TelephonyManager.CARRIER_PRIVILEGE_STATUS_HAS_ACCESS);
6980 
6981         mLooper.startAutoDispatch();
6982         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
6983                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
6984                         TEST_FEATURE_ID));
6985         mLooper.stopAutoDispatchAndIgnoreExceptions();
6986 
6987         verify(mWifiNetworkSuggestionsManager).add(
6988                 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
6989     }
6990 
6991     /**
6992      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network
6993      * suggestions for privileged app when DISALLOW_ADD_WIFI_CONFIG user restriction is set.
6994      */
6995     @Test
testAddNetworkSuggestionsIsAllowedForPrivilegedAppWithUserRestriction()6996     public void testAddNetworkSuggestionsIsAllowedForPrivilegedAppWithUserRestriction() {
6997         assumeTrue(SdkLevel.isAtLeastT());
6998         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
6999                 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
7000         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7001                 any())).thenReturn(true);
7002         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
7003                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
7004 
7005         mLooper.startAutoDispatch();
7006         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
7007                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7008                         TEST_FEATURE_ID));
7009         mLooper.stopAutoDispatchAndIgnoreExceptions();
7010 
7011         verify(mWifiNetworkSuggestionsManager).add(
7012                 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
7013     }
7014 
7015     /**
7016      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network
7017      * suggestions for system app when DISALLOW_ADD_WIFI_CONFIG user restriction is set.
7018      */
7019     @Test
testAddNetworkSuggestionsIsAllowedForSystemAppWithUserRestriction()7020     public void testAddNetworkSuggestionsIsAllowedForSystemAppWithUserRestriction() {
7021         assumeTrue(SdkLevel.isAtLeastT());
7022         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
7023                 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
7024         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7025                 any())).thenReturn(true);
7026         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
7027 
7028         mLooper.startAutoDispatch();
7029         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
7030                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7031                         TEST_FEATURE_ID));
7032         mLooper.stopAutoDispatchAndIgnoreExceptions();
7033 
7034         verify(mWifiNetworkSuggestionsManager).add(
7035                 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
7036     }
7037 
7038     /**
7039      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to add network
7040      * suggestions for admin app when DISALLOW_ADD_WIFI_CONFIG user restriction is set.
7041      */
7042     @Test
testAddNetworkSuggestionsIsAllowedForAdminAppWithUserRestriction()7043     public void testAddNetworkSuggestionsIsAllowedForAdminAppWithUserRestriction() {
7044         assumeTrue(SdkLevel.isAtLeastT());
7045         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
7046                 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
7047         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7048                 any())).thenReturn(true);
7049         when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(true);
7050 
7051         mLooper.startAutoDispatch();
7052         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
7053                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7054                         TEST_FEATURE_ID));
7055         mLooper.stopAutoDispatchAndIgnoreExceptions();
7056 
7057         verify(mWifiNetworkSuggestionsManager).add(
7058                 any(), eq(Binder.getCallingUid()), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
7059     }
7060 
7061     /**
7062      * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to add network
7063      * suggestions for normal app when DISALLOW_ADD_WIFI_CONFIG user restriction is set.
7064      */
7065     @Test
testAddNetworkSuggestionsIsNotAllowedForNormalAppWithUserRestriction()7066     public void testAddNetworkSuggestionsIsNotAllowedForNormalAppWithUserRestriction() {
7067         assumeTrue(SdkLevel.isAtLeastT());
7068         when(mWifiNetworkSuggestionsManager.add(any(), anyInt(), anyString(),
7069                 nullable(String.class))).thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
7070         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7071                 any())).thenReturn(true);
7072 
7073         mLooper.startAutoDispatch();
7074         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_RESTRICTED_BY_ADMIN,
7075                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7076                         TEST_FEATURE_ID));
7077         mLooper.stopAutoDispatchAndIgnoreExceptions();
7078 
7079         verify(mWifiNetworkSuggestionsManager, never()).add(any(), eq(Binder.getCallingUid()),
7080                 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
7081     }
7082 
7083     /**
7084      * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to add network
7085      * suggestions when the looper sync call times out.
7086      */
7087     @Test
testAddNetworkSuggestionsFailureInRunWithScissors()7088     public void testAddNetworkSuggestionsFailureInRunWithScissors() {
7089         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
7090 
7091         mLooper.startAutoDispatch();
7092         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
7093                 mWifiServiceImpl.addNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7094                         TEST_FEATURE_ID));
7095         mLooper.stopAutoDispatchAndIgnoreExceptions();
7096 
7097         verify(mWifiNetworkSuggestionsManager, never()).add(any(), eq(Binder.getCallingUid()),
7098                 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID));
7099     }
7100 
7101     /**
7102      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to remove network
7103      * suggestions.
7104      */
7105     @Test
testRemoveNetworkSuggestions()7106     public void testRemoveNetworkSuggestions() {
7107         when(mWifiNetworkSuggestionsManager.remove(any(), anyInt(), anyString(), anyInt()))
7108                 .thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID);
7109         mLooper.startAutoDispatch();
7110         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID,
7111                 mWifiServiceImpl.removeNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7112                         ACTION_REMOVE_SUGGESTION_DISCONNECT));
7113         mLooper.stopAutoDispatchAndIgnoreExceptions();
7114 
7115         when(mWifiNetworkSuggestionsManager.remove(any(), anyInt(), anyString(),
7116                 anyInt()))
7117                 .thenReturn(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS);
7118         mLooper.startAutoDispatch();
7119         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
7120                 mWifiServiceImpl.removeNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7121                         ACTION_REMOVE_SUGGESTION_DISCONNECT));
7122         mLooper.stopAutoDispatchAndIgnoreExceptions();
7123 
7124         verify(mWifiNetworkSuggestionsManager, times(2)).remove(any(), anyInt(),
7125                 eq(TEST_PACKAGE_NAME), eq(ACTION_REMOVE_SUGGESTION_DISCONNECT));
7126     }
7127 
7128     /**
7129      * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to remove network
7130      * suggestions when the looper sync call times out.
7131      */
7132     @Test
testRemoveNetworkSuggestionsFailureInRunWithScissors()7133     public void testRemoveNetworkSuggestionsFailureInRunWithScissors() {
7134         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
7135 
7136         mLooper.startAutoDispatch();
7137         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_INTERNAL,
7138                 mWifiServiceImpl.removeNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME,
7139                 ACTION_REMOVE_SUGGESTION_DISCONNECT));
7140         mLooper.stopAutoDispatchAndIgnoreExceptions();
7141 
7142         verify(mWifiNetworkSuggestionsManager, never()).remove(any(), anyInt(),
7143                 eq(TEST_PACKAGE_NAME), eq(ACTION_REMOVE_SUGGESTION_DISCONNECT));
7144     }
7145 
7146     /**
7147      * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to remove network
7148      * suggestions when the action is invalid.
7149      */
7150     @Test
testRemoveNetworkSuggestionsFailureWithInvalidAction()7151     public void testRemoveNetworkSuggestionsFailureWithInvalidAction() {
7152         mLooper.startAutoDispatch();
7153         assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_ERROR_REMOVE_INVALID,
7154                 mWifiServiceImpl.removeNetworkSuggestions(mock(List.class), TEST_PACKAGE_NAME, 0));
7155         mLooper.stopAutoDispatchAndIgnoreExceptions();
7156         verify(mWifiNetworkSuggestionsManager, never()).remove(any(), anyInt(),
7157                 eq(TEST_PACKAGE_NAME), anyInt());
7158     }
7159 
7160     @Test(expected = SecurityException.class)
testRemoveNonCallerConfiguredNetworks_NormalAppCaller_ThrowsException()7161     public void testRemoveNonCallerConfiguredNetworks_NormalAppCaller_ThrowsException() {
7162         mWifiServiceImpl.removeNonCallerConfiguredNetworks(TEST_PACKAGE_NAME);
7163     }
7164 
7165     @Test(expected = SecurityException.class)
testRemoveNonCallerConfiguredNetworks_CallerIsProfileOwner_ThrowsException()7166     public void testRemoveNonCallerConfiguredNetworks_CallerIsProfileOwner_ThrowsException() {
7167         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
7168                 .thenReturn(true);
7169         mWifiServiceImpl.removeNonCallerConfiguredNetworks(TEST_PACKAGE_NAME);
7170     }
7171 
7172     @Test
testRemoveNonCallerConfiguredNetworks_NetworksRemoved()7173     public void testRemoveNonCallerConfiguredNetworks_NetworksRemoved() {
7174         final int callerUid = Binder.getCallingUid();
7175         when(mWifiPermissionsUtil.isOrganizationOwnedDeviceAdmin(
7176                 Binder.getCallingUid(), TEST_PACKAGE_NAME)).thenReturn(true);
7177 
7178         mLooper.startAutoDispatch();
7179         mWifiServiceImpl.removeNonCallerConfiguredNetworks(TEST_PACKAGE_NAME);
7180         mLooper.stopAutoDispatchAndIgnoreExceptions();
7181 
7182         verify(mWifiConfigManager).removeNonCallerConfiguredNetwork(eq(callerUid));
7183     }
7184 
7185     /**
7186      * Ensure that we invoke {@link WifiNetworkSuggestionsManager} to get network
7187      * suggestions.
7188      */
7189     @Test
testGetNetworkSuggestions()7190     public void testGetNetworkSuggestions() {
7191         List<WifiNetworkSuggestion> testList = new ArrayList<>();
7192         when(mWifiNetworkSuggestionsManager.get(anyString(), anyInt())).thenReturn(testList);
7193         mLooper.startAutoDispatch();
7194         assertEquals(testList, mWifiServiceImpl.getNetworkSuggestions(TEST_PACKAGE_NAME));
7195         mLooper.stopAutoDispatchAndIgnoreExceptions();
7196 
7197         verify(mWifiNetworkSuggestionsManager).get(eq(TEST_PACKAGE_NAME), anyInt());
7198     }
7199 
7200     /**
7201      * Ensure that we don't invoke {@link WifiNetworkSuggestionsManager} to get network
7202      * suggestions when the looper sync call times out.
7203      */
7204     @Test
testGetNetworkSuggestionsFailureInRunWithScissors()7205     public void testGetNetworkSuggestionsFailureInRunWithScissors() {
7206         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
7207 
7208         mLooper.startAutoDispatch();
7209         assertTrue(mWifiServiceImpl.getNetworkSuggestions(TEST_PACKAGE_NAME).isEmpty());
7210         mLooper.stopAutoDispatchAndIgnoreExceptions();
7211 
7212         verify(mWifiNetworkSuggestionsManager, never()).get(eq(TEST_PACKAGE_NAME), anyInt());
7213     }
7214 
7215     /**
7216      * Verify that if the caller has NETWORK_SETTINGS permission, then it can invoke
7217      * {@link WifiManager#disableEphemeralNetwork(String)}.
7218      */
7219     @Test
testDisableEphemeralNetworkWithNetworkSettingsPerm()7220     public void testDisableEphemeralNetworkWithNetworkSettingsPerm() throws Exception {
7221         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
7222                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
7223         mWifiServiceImpl.disableEphemeralNetwork(new String(), TEST_PACKAGE_NAME);
7224         mLooper.dispatchAll();
7225         verify(mWifiConfigManager).userTemporarilyDisabledNetwork(anyString(), anyInt());
7226     }
7227 
7228     /**
7229      * Verify that if the caller does not have NETWORK_SETTINGS permission, then it cannot invoke
7230      * {@link WifiManager#disableEphemeralNetwork(String)}.
7231      */
7232     @Test
testDisableEphemeralNetworkWithoutNetworkSettingsPerm()7233     public void testDisableEphemeralNetworkWithoutNetworkSettingsPerm() throws Exception {
7234         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
7235                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
7236         mWifiServiceImpl.disableEphemeralNetwork(new String(), TEST_PACKAGE_NAME);
7237         mLooper.dispatchAll();
7238         verify(mWifiConfigManager, never()).userTemporarilyDisabledNetwork(anyString(), anyInt());
7239     }
7240 
7241     /**
7242      * Verify getting the factory MAC address.
7243      */
7244     @Test
testGetFactoryMacAddresses()7245     public void testGetFactoryMacAddresses() throws Exception {
7246         when(mClientModeManager.getFactoryMacAddress()).thenReturn(TEST_FACTORY_MAC);
7247         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
7248         mLooper.startAutoDispatch();
7249         final String[] factoryMacs = mWifiServiceImpl.getFactoryMacAddresses();
7250         mLooper.stopAutoDispatchAndIgnoreExceptions();
7251         assertEquals(1, factoryMacs.length);
7252         assertEquals(TEST_FACTORY_MAC, factoryMacs[0]);
7253         verify(mClientModeManager).getFactoryMacAddress();
7254     }
7255 
7256     /**
7257      * Verify getting the factory MAC address returns null when posting the runnable to handler
7258      * fails.
7259      */
7260     @Test
testGetFactoryMacAddressesPostFail()7261     public void testGetFactoryMacAddressesPostFail() throws Exception {
7262         mWifiServiceImpl = makeWifiServiceImplWithMockRunnerWhichTimesOut();
7263 
7264         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
7265         mLooper.startAutoDispatch();
7266         assertArrayEquals(new String[0], mWifiServiceImpl.getFactoryMacAddresses());
7267         mLooper.stopAutoDispatchAndIgnoreExceptions();
7268         verify(mClientModeManager, never()).getFactoryMacAddress();
7269     }
7270 
7271     /**
7272      * Verify getting the factory MAC address returns null when the lower layers fail.
7273      */
7274     @Test
testGetFactoryMacAddressesFail()7275     public void testGetFactoryMacAddressesFail() throws Exception {
7276         when(mClientModeManager.getFactoryMacAddress()).thenReturn(null);
7277         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
7278         mLooper.startAutoDispatch();
7279         assertArrayEquals(new String[0], mWifiServiceImpl.getFactoryMacAddresses());
7280         mLooper.stopAutoDispatchAndIgnoreExceptions();
7281         verify(mClientModeManager).getFactoryMacAddress();
7282     }
7283 
7284     /**
7285      * Verify getting the factory MAC address throws a SecurityException if the calling app
7286      * doesn't have NETWORK_SETTINGS permission.
7287      */
7288     @Test
testGetFactoryMacAddressesFailNoNetworkSettingsPermission()7289     public void testGetFactoryMacAddressesFailNoNetworkSettingsPermission() throws Exception {
7290         when(mClientModeManager.getFactoryMacAddress()).thenReturn(TEST_FACTORY_MAC);
7291         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
7292         try {
7293             mLooper.startAutoDispatch();
7294             mWifiServiceImpl.getFactoryMacAddresses();
7295             mLooper.stopAutoDispatchAndIgnoreExceptions();
7296             fail();
7297         } catch (SecurityException e) {
7298             assertTrue("Exception message should contain 'factory MAC'",
7299                     e.toString().contains("factory MAC"));
7300         }
7301     }
7302 
7303     /**
7304      * Verify that a call to setDeviceMobilityState throws a SecurityException if the
7305      * caller does not have WIFI_SET_DEVICE_MOBILITY_STATE permission.
7306      */
7307     @Test(expected = SecurityException.class)
setDeviceMobilityStateThrowsSecurityExceptionOnMissingPermissions()7308     public void setDeviceMobilityStateThrowsSecurityExceptionOnMissingPermissions() {
7309         doThrow(new SecurityException()).when(mContext)
7310                 .enforceCallingOrSelfPermission(
7311                         eq(android.Manifest.permission.WIFI_SET_DEVICE_MOBILITY_STATE),
7312                         eq("WifiService"));
7313         mWifiServiceImpl.setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7314     }
7315 
7316     /**
7317      * Verifies that setDeviceMobilityState runs on a separate handler thread.
7318      */
7319     @Test
setDeviceMobilityStateRunsOnHandler()7320     public void setDeviceMobilityStateRunsOnHandler() {
7321         mWifiServiceImpl.setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7322         verify(mWifiConnectivityManager, never())
7323                 .setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7324         verify(mWifiHealthMonitor, never())
7325                 .setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7326         verify(mWifiDataStall, never())
7327                 .setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7328         mLooper.dispatchAll();
7329         verify(mWifiConnectivityManager).setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7330         verify(mWifiHealthMonitor).setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7331         verify(mWifiDataStall).setDeviceMobilityState(DEVICE_MOBILITY_STATE_STATIONARY);
7332     }
7333 
7334     /**
7335      * Verify that a call to addOnWifiUsabilityStatsListener throws a SecurityException if
7336      * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission.
7337      */
7338     @Test
testAddStatsListenerThrowsSecurityExceptionOnMissingPermissions()7339     public void testAddStatsListenerThrowsSecurityExceptionOnMissingPermissions() {
7340         doThrow(new SecurityException()).when(mContext)
7341                 .enforceCallingOrSelfPermission(
7342                         eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE),
7343                         eq("WifiService"));
7344         try {
7345             mWifiServiceImpl.addOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener);
7346             fail("expected SecurityException");
7347         } catch (SecurityException expected) {
7348         }
7349     }
7350 
7351     /**
7352      * Verify that a call to addOnWifiUsabilityStatsListener throws an IllegalArgumentException
7353      * if the parameters are not provided.
7354      */
7355     @Test
testAddStatsListenerThrowsIllegalArgumentExceptionOnInvalidArguments()7356     public void testAddStatsListenerThrowsIllegalArgumentExceptionOnInvalidArguments() {
7357         try {
7358             mWifiServiceImpl.addOnWifiUsabilityStatsListener(null);
7359             fail("expected IllegalArgumentException");
7360         } catch (IllegalArgumentException expected) {
7361         }
7362     }
7363 
7364     /**
7365      * Verify that a call to removeOnWifiUsabilityStatsListener throws a SecurityException if
7366      * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission.
7367      */
7368     @Test
testRemoveStatsListenerThrowsSecurityExceptionOnMissingPermissions()7369     public void testRemoveStatsListenerThrowsSecurityExceptionOnMissingPermissions() {
7370         doThrow(new SecurityException()).when(mContext)
7371                 .enforceCallingOrSelfPermission(
7372                         eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE),
7373                         eq("WifiService"));
7374         try {
7375             mWifiServiceImpl.removeOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener);
7376             fail("expected SecurityException");
7377         } catch (SecurityException expected) {
7378         }
7379     }
7380 
7381     /**
7382      * Verify that addOnWifiUsabilityStatsListener adds listener to {@link WifiMetrics}.
7383      */
7384     @Test
testAddOnWifiUsabilityStatsListenerAndVerify()7385     public void testAddOnWifiUsabilityStatsListenerAndVerify() throws Exception {
7386         mWifiServiceImpl.addOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener);
7387         mLooper.dispatchAll();
7388         verify(mWifiMetrics).addOnWifiUsabilityListener(mOnWifiUsabilityStatsListener);
7389     }
7390 
7391     /**
7392      * Verify that removeOnWifiUsabilityStatsListener removes listener from
7393      * {@link WifiMetrics}.
7394      */
7395     @Test
testRemoveOnWifiUsabilityStatsListenerAndVerify()7396     public void testRemoveOnWifiUsabilityStatsListenerAndVerify() throws Exception {
7397         mWifiServiceImpl.removeOnWifiUsabilityStatsListener(mOnWifiUsabilityStatsListener);
7398         mLooper.dispatchAll();
7399         verify(mWifiMetrics).removeOnWifiUsabilityListener(mOnWifiUsabilityStatsListener);
7400     }
7401 
7402     /**
7403      * Verify that a call to updateWifiUsabilityScore throws a SecurityException if the
7404      * caller does not have UPDATE_WIFI_USABILITY_SCORE permission.
7405      */
7406     @Test
testUpdateWifiUsabilityScoreThrowsSecurityExceptionOnMissingPermissions()7407     public void testUpdateWifiUsabilityScoreThrowsSecurityExceptionOnMissingPermissions() {
7408         doThrow(new SecurityException()).when(mContext)
7409                 .enforceCallingOrSelfPermission(
7410                 eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE),
7411                 eq("WifiService"));
7412         try {
7413             mWifiServiceImpl.updateWifiUsabilityScore(anyInt(), anyInt(), 15);
7414             fail("expected SecurityException");
7415         } catch (SecurityException expected) {
7416         }
7417     }
7418 
7419     /**
7420      * Verify that mClientModeManager in WifiServiceImpl is being updated on Wifi usability score
7421      * update event.
7422      */
7423     @Test
testWifiUsabilityScoreUpdateAfterScoreEvent()7424     public void testWifiUsabilityScoreUpdateAfterScoreEvent() {
7425         mWifiServiceImpl.updateWifiUsabilityScore(5, 10, 15);
7426         mLooper.dispatchAll();
7427         verify(mWifiMetrics).incrementWifiUsabilityScoreCount(WIFI_IFACE_NAME, 5, 10, 15);
7428     }
7429 
startLohsAndTethering(boolean isApConcurrencySupported)7430     private void startLohsAndTethering(boolean isApConcurrencySupported) throws Exception {
7431         // initialization
7432         when(mActiveModeWarden.canRequestMoreSoftApManagers(
7433                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))))
7434                 .thenReturn(isApConcurrencySupported);
7435         // For these tests, always use distinct interface names for LOHS and tethered.
7436         mLohsInterfaceName = WIFI_IFACE_NAME2;
7437 
7438         setupLocalOnlyHotspot();
7439         reset(mActiveModeWarden);
7440 
7441         when(mActiveModeWarden.canRequestMoreSoftApManagers(
7442                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME))))
7443                 .thenReturn(isApConcurrencySupported);
7444 
7445         // start tethering
7446         mLooper.startAutoDispatch();
7447         boolean tetheringResult = mWifiServiceImpl.startSoftAp(null, TEST_PACKAGE_NAME);
7448         mLooper.stopAutoDispatchAndIgnoreExceptions();
7449         assertTrue(tetheringResult);
7450         verify(mActiveModeWarden).startSoftAp(any(),
7451                 eq(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME)));
7452         mWifiServiceImpl.updateInterfaceIpState(WIFI_IFACE_NAME, IFACE_IP_MODE_TETHERED);
7453         mLooper.dispatchAll();
7454     }
7455 
7456     /**
7457      * Verify LOHS gets stopped when trying to start tethering concurrently on devices that
7458      * doesn't support dual AP operation.
7459      */
7460     @Test
testStartLohsAndTethering1AP()7461     public void testStartLohsAndTethering1AP() throws Exception {
7462         startLohsAndTethering(false);
7463 
7464         // verify LOHS got stopped
7465         verify(mLohsCallback).onHotspotFailed(anyInt());
7466         verify(mActiveModeWarden).stopSoftAp(WifiManager.IFACE_IP_MODE_LOCAL_ONLY);
7467     }
7468 
7469     /**
7470      * Verify LOHS doesn't get stopped when trying to start tethering concurrently on devices
7471      * that does support dual AP operation.
7472      */
7473     @Test
testStartLohsAndTethering2AP()7474     public void testStartLohsAndTethering2AP() throws Exception {
7475         startLohsAndTethering(true);
7476 
7477         // verify LOHS didn't get stopped
7478         verifyZeroInteractions(ignoreStubs(mLohsCallback));
7479         verify(mActiveModeWarden, never()).stopSoftAp(anyInt());
7480     }
7481 
7482     /**
7483      * Verify that the call to startDppAsConfiguratorInitiator throws a security exception when the
7484      * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD.
7485      */
7486     @Test(expected = SecurityException.class)
testStartDppAsConfiguratorInitiatorWithoutPermissions()7487     public void testStartDppAsConfiguratorInitiatorWithoutPermissions() {
7488         mWifiServiceImpl.startDppAsConfiguratorInitiator(mAppBinder, TEST_PACKAGE_NAME, DPP_URI,
7489                 1, 1, mDppCallback);
7490     }
7491 
7492     /**
7493      * Verify that the call to startDppAsEnrolleeInitiator throws a security exception when the
7494      * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD.
7495      */
7496     @Test(expected = SecurityException.class)
testStartDppAsEnrolleeInitiatorWithoutPermissions()7497     public void testStartDppAsEnrolleeInitiatorWithoutPermissions() {
7498         mWifiServiceImpl.startDppAsEnrolleeInitiator(mAppBinder, DPP_URI, mDppCallback);
7499     }
7500 
7501     /**
7502      * Verify that the call to startDppAsEnrolleeResponder throws a security exception when the
7503      * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD.
7504      */
7505     @Test(expected = SecurityException.class)
testStartDppAsEnrolleeResponderWithoutPermissions()7506     public void testStartDppAsEnrolleeResponderWithoutPermissions() {
7507         assumeTrue(SdkLevel.isAtLeastS());
7508         mWifiServiceImpl.startDppAsEnrolleeResponder(mAppBinder, DPP_PRODUCT_INFO,
7509                 EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1, mDppCallback);
7510     }
7511 
7512     /**
7513      * Verify that a call to StartDppAsEnrolleeResponder throws an IllegalArgumentException
7514      * if the deviceInfo length exceeds the max allowed length.
7515      */
7516     @Test(expected = SecurityException.class)
testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnDeviceInfoMaxLen()7517     public void testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnDeviceInfoMaxLen() {
7518         assumeTrue(SdkLevel.isAtLeastS());
7519         try {
7520             StringBuilder sb = new StringBuilder();
7521             sb.append(Strings.repeat("a",
7522                     WifiManager.getEasyConnectMaxAllowedResponderDeviceInfoLength() + 2));
7523             String deviceInfo = sb.toString();
7524             mWifiServiceImpl.startDppAsEnrolleeResponder(mAppBinder, deviceInfo,
7525                     EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1, mDppCallback);
7526             fail("expected IllegalArgumentException");
7527         } catch (IllegalArgumentException expected) {
7528         }
7529     }
7530 
7531     /**
7532      * Verify that a call to StartDppAsEnrolleeResponder throws an IllegalArgumentException
7533      * if the deviceInfo contains characters which are not allowed as per spec (For example
7534      * semicolon)
7535      */
7536     @Test(expected = SecurityException.class)
testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnWrongDeviceInfo()7537     public void testStartDppAsEnrolleeResponderThrowsIllegalArgumentExceptionOnWrongDeviceInfo() {
7538         assumeTrue(SdkLevel.isAtLeastS());
7539         try {
7540             mWifiServiceImpl.startDppAsEnrolleeResponder(mAppBinder, "DPP;TESTER",
7541                     EASY_CONNECT_CRYPTOGRAPHY_CURVE_PRIME256V1, mDppCallback);
7542             fail("expected IllegalArgumentException");
7543         } catch (IllegalArgumentException expected) {
7544         }
7545     }
7546 
7547     /**
7548      * Verify that the call to stopDppSession throws a security exception when the
7549      * caller doesn't have NETWORK_SETTINGS permissions or NETWORK_SETUP_WIZARD.
7550      */
7551     @Test(expected = SecurityException.class)
testStopDppSessionWithoutPermissions()7552     public void testStopDppSessionWithoutPermissions() {
7553         try {
7554             mWifiServiceImpl.stopDppSession();
7555         } catch (RemoteException e) {
7556         }
7557     }
7558 
7559     /**
7560      * Verifies that configs can be removed.
7561      */
7562     @Test
testRemoveNetworkIsAllowedForAppsTargetingBelowQSdk()7563     public void testRemoveNetworkIsAllowedForAppsTargetingBelowQSdk() {
7564         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7565                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7566         when(mWifiConfigManager.removeNetwork(eq(0), anyInt(), anyString())).thenReturn(true);
7567         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7568                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
7569 
7570         mLooper.startAutoDispatch();
7571         boolean result = mWifiServiceImpl.removeNetwork(0, TEST_PACKAGE_NAME);
7572         mLooper.stopAutoDispatchAndIgnoreExceptions();
7573 
7574         assertTrue(result);
7575         verify(mWifiConfigManager).removeNetwork(anyInt(), anyInt(), anyString());
7576     }
7577 
7578     /**
7579      * Verify that addOrUpdatePasspointConfiguration is allowed for apps targeting below R SDK.
7580      */
7581     @Test
addOrUpdatePasspointConfigIsAllowedForAppsTargetingBelowRSdk()7582     public void addOrUpdatePasspointConfigIsAllowedForAppsTargetingBelowRSdk() throws Exception {
7583         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7584                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7585         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7586                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(true);
7587         PasspointConfiguration config = new PasspointConfiguration();
7588         HomeSp homeSp = new HomeSp();
7589         homeSp.setFqdn("test.com");
7590         config.setHomeSp(homeSp);
7591 
7592         when(mPasspointManager.addOrUpdateProvider(
7593                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7594                 .thenReturn(true);
7595         mLooper.startAutoDispatch();
7596         assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7597         mLooper.stopAutoDispatchAndIgnoreExceptions();
7598         reset(mPasspointManager);
7599 
7600         when(mPasspointManager.addOrUpdateProvider(
7601                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7602                 .thenReturn(false);
7603         mLooper.startAutoDispatch();
7604         assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7605         mLooper.stopAutoDispatchAndIgnoreExceptions();
7606     }
7607 
7608     /**
7609      * Verify that addOrUpdatePasspointConfiguration is not allowed for apps targeting R SDK.
7610      */
7611     @Test
addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingRSdk()7612     public void addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingRSdk() throws Exception {
7613         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7614                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7615         PasspointConfiguration config = new PasspointConfiguration();
7616         HomeSp homeSp = new HomeSp();
7617         homeSp.setFqdn("test.com");
7618         config.setHomeSp(homeSp);
7619 
7620         when(mPasspointManager.addOrUpdateProvider(
7621                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7622                 .thenReturn(true);
7623         mLooper.startAutoDispatch();
7624         assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7625         mLooper.stopAutoDispatchAndIgnoreExceptions();
7626         verify(mPasspointManager, never())
7627                 .addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), anyBoolean(),
7628                         eq(false));
7629 
7630     }
7631 
7632     /**
7633      * Verify that addOrUpdatePasspointConfiguration is allowed for Settings apps.
7634      */
7635     @Test
addOrUpdatePasspointConfigIsAllowedSettingsApp()7636     public void addOrUpdatePasspointConfigIsAllowedSettingsApp() throws Exception {
7637         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
7638                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
7639         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7640                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false);
7641         PasspointConfiguration config = new PasspointConfiguration();
7642         HomeSp homeSp = new HomeSp();
7643         homeSp.setFqdn("test.com");
7644         config.setHomeSp(homeSp);
7645 
7646         when(mPasspointManager.addOrUpdateProvider(
7647                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7648                 .thenReturn(true);
7649         mLooper.startAutoDispatch();
7650         assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7651         mLooper.stopAutoDispatchAndIgnoreExceptions();
7652         verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(),
7653                 anyBoolean(), eq(false));
7654     }
7655 
7656     /**
7657      * Verify that addOrUpdatePasspointConfiguration is allowed for System apps.
7658      */
7659     @Test
addOrUpdatePasspointConfigIsAllowedSystemApp()7660     public void addOrUpdatePasspointConfigIsAllowedSystemApp() throws Exception {
7661         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7662                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7663         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7664                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false);
7665         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
7666         PasspointConfiguration config = new PasspointConfiguration();
7667         HomeSp homeSp = new HomeSp();
7668         homeSp.setFqdn("test.com");
7669         config.setHomeSp(homeSp);
7670 
7671         when(mPasspointManager.addOrUpdateProvider(
7672                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7673                 .thenReturn(true);
7674         mLooper.startAutoDispatch();
7675         assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7676         mLooper.stopAutoDispatchAndIgnoreExceptions();
7677         verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(),
7678                 anyBoolean(), eq(false));
7679     }
7680 
7681     /**
7682      * Verify that addOrUpdatePasspointConfiguration is allowed for DeviceOwner apps.
7683      */
7684     @Test
addOrUpdatePasspointConfigIsAllowedSystemAlertDOApp()7685     public void addOrUpdatePasspointConfigIsAllowedSystemAlertDOApp() throws Exception {
7686         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7687                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7688         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7689                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false);
7690         when(mWifiPermissionsUtil.isDeviceOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
7691                 .thenReturn(true);
7692         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
7693                 .thenReturn(true);
7694         PasspointConfiguration config = new PasspointConfiguration();
7695         HomeSp homeSp = new HomeSp();
7696         homeSp.setFqdn("test.com");
7697         config.setHomeSp(homeSp);
7698 
7699         when(mPasspointManager.addOrUpdateProvider(
7700                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7701                 .thenReturn(true);
7702         mLooper.startAutoDispatch();
7703         assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7704         mLooper.stopAutoDispatchAndIgnoreExceptions();
7705         verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(),
7706                 anyBoolean(), eq(false));
7707     }
7708 
7709     /**
7710      * Verify that addOrUpdatePasspointConfiguration is allowed for ProfileOwner apps.
7711      */
7712     @Test
addOrUpdatePasspointConfigIsAllowedSystemAlertPOApp()7713     public void addOrUpdatePasspointConfigIsAllowedSystemAlertPOApp() throws Exception {
7714         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7715                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7716         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7717                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false);
7718         when(mWifiPermissionsUtil.isProfileOwner(Binder.getCallingUid(), TEST_PACKAGE_NAME))
7719                 .thenReturn(true);
7720         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
7721                 .thenReturn(true);
7722         PasspointConfiguration config = new PasspointConfiguration();
7723         HomeSp homeSp = new HomeSp();
7724         homeSp.setFqdn("test.com");
7725         config.setHomeSp(homeSp);
7726 
7727         when(mPasspointManager.addOrUpdateProvider(
7728                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7729                 .thenReturn(true);
7730         mLooper.startAutoDispatch();
7731         assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7732         mLooper.stopAutoDispatchAndIgnoreExceptions();
7733         verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(),
7734                 anyBoolean(), eq(false));
7735     }
7736 
7737     /**
7738      * Verify that addOrUpdatePasspointConfiguration is not allowed for apps targeting below R SDK
7739      * when the DISALLOW_ADD_WIFI_CONFIG user restriction is set.
7740      */
7741     @Test
addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingBelowRSdkWithUserRestriction()7742     public void addOrUpdatePasspointConfigIsNotAllowedForAppsTargetingBelowRSdkWithUserRestriction()
7743             throws Exception {
7744         assumeTrue(SdkLevel.isAtLeastT());
7745         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7746                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7747         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7748                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(true);
7749         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7750                 any())).thenReturn(true);
7751         PasspointConfiguration config = new PasspointConfiguration();
7752         HomeSp homeSp = new HomeSp();
7753         homeSp.setFqdn("test.com");
7754         config.setHomeSp(homeSp);
7755 
7756         when(mPasspointManager.addOrUpdateProvider(
7757                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7758                 .thenReturn(true);
7759         mLooper.startAutoDispatch();
7760         assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7761         mLooper.stopAutoDispatchAndIgnoreExceptions();
7762         verify(mPasspointManager, never())
7763                 .addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), anyBoolean(),
7764                         eq(false));
7765     }
7766 
7767     /**
7768      * Verify that addOrUpdatePasspointConfiguration is not allowed for system apps
7769      * when the DISALLOW_ADD_WIFI_CONFIG user restriction is set.
7770      */
7771     @Test
addOrUpdatePasspointConfigIsNotAllowedForSystemAppWithUserRestriction()7772     public void addOrUpdatePasspointConfigIsNotAllowedForSystemAppWithUserRestriction()
7773             throws Exception {
7774         assumeTrue(SdkLevel.isAtLeastT());
7775         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7776                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7777         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7778                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false);
7779         when(mWifiPermissionsUtil.isSystem(anyString(), anyInt())).thenReturn(true);
7780         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7781                 any())).thenReturn(true);
7782         PasspointConfiguration config = new PasspointConfiguration();
7783         HomeSp homeSp = new HomeSp();
7784         homeSp.setFqdn("test.com");
7785         config.setHomeSp(homeSp);
7786 
7787         when(mPasspointManager.addOrUpdateProvider(
7788                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7789                 .thenReturn(true);
7790         mLooper.startAutoDispatch();
7791         assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7792         mLooper.stopAutoDispatchAndIgnoreExceptions();
7793         verify(mPasspointManager, never())
7794                 .addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(), anyBoolean(),
7795                         eq(false));
7796     }
7797 
7798     /**
7799      * Verify that addOrUpdatePasspointConfiguration is allowed for admin apps
7800      * when the DISALLOW_ADD_WIFI_CONFIG user restriction is set.
7801      */
7802     @Test
addOrUpdatePasspointConfigIsAllowedSystemAlertAdminAppWithUserRestriction()7803     public void addOrUpdatePasspointConfigIsAllowedSystemAlertAdminAppWithUserRestriction()
7804             throws Exception {
7805         assumeTrue(SdkLevel.isAtLeastT());
7806         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7807                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7808         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7809                 eq(Build.VERSION_CODES.R), anyInt())).thenReturn(false);
7810         when(mWifiPermissionsUtil.isAdmin(Binder.getCallingUid(), TEST_PACKAGE_NAME))
7811                 .thenReturn(true);
7812         when(mUserManager.hasUserRestrictionForUser(eq(UserManager.DISALLOW_ADD_WIFI_CONFIG),
7813                 any())).thenReturn(true);
7814         PasspointConfiguration config = new PasspointConfiguration();
7815         HomeSp homeSp = new HomeSp();
7816         homeSp.setFqdn("test.com");
7817         config.setHomeSp(homeSp);
7818 
7819         when(mPasspointManager.addOrUpdateProvider(
7820                 config, Binder.getCallingUid(), TEST_PACKAGE_NAME, false, true, false))
7821                 .thenReturn(true);
7822         mLooper.startAutoDispatch();
7823         assertTrue(mWifiServiceImpl.addOrUpdatePasspointConfiguration(config, TEST_PACKAGE_NAME));
7824         mLooper.stopAutoDispatchAndIgnoreExceptions();
7825         verify(mPasspointManager).addOrUpdateProvider(any(), anyInt(), anyString(), anyBoolean(),
7826                 anyBoolean(), eq(false));
7827     }
7828 
7829     /**
7830      * Verify that removePasspointConfiguration will redirect calls to {@link PasspointManager}
7831      * and returning the result that's returned from {@link PasspointManager}.
7832      */
7833     @Test
removePasspointConfig()7834     public void removePasspointConfig() throws Exception {
7835         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
7836 
7837         String fqdn = "test.com";
7838         when(mPasspointManager.removeProvider(anyInt(), anyBoolean(), isNull(), eq(fqdn)))
7839                 .thenReturn(true);
7840         mLooper.startAutoDispatch();
7841         assertTrue(mWifiServiceImpl.removePasspointConfiguration(fqdn, TEST_PACKAGE_NAME));
7842         mLooper.stopAutoDispatchAndIgnoreExceptions();
7843         reset(mPasspointManager);
7844 
7845         when(mPasspointManager.removeProvider(anyInt(), anyBoolean(), isNull(), eq(fqdn)))
7846                 .thenReturn(false);
7847         mLooper.startAutoDispatch();
7848         assertFalse(mWifiServiceImpl.removePasspointConfiguration(fqdn, TEST_PACKAGE_NAME));
7849         mLooper.stopAutoDispatchAndIgnoreExceptions();
7850     }
7851 
7852     /**
7853      * Test that DISABLE_NETWORK returns failure to public API when WifiConfigManager returns
7854      * failure.
7855      */
7856     @Test
testDisableNetworkFailureAppBelowQSdk()7857     public void testDisableNetworkFailureAppBelowQSdk() throws Exception {
7858         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
7859                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
7860         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
7861                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
7862         when(mWifiConfigManager.disableNetwork(anyInt(), anyInt(), anyString())).thenReturn(false);
7863 
7864         mLooper.startAutoDispatch();
7865         boolean succeeded = mWifiServiceImpl.disableNetwork(0, TEST_PACKAGE_NAME);
7866         mLooper.stopAutoDispatchAndIgnoreExceptions();
7867         assertFalse(succeeded);
7868     }
7869 
7870     @Test
testSetNetworkSelectionConfig()7871     public void testSetNetworkSelectionConfig() throws Exception {
7872         assumeTrue(SdkLevel.isAtLeastT());
7873 
7874         WifiNetworkSelectionConfig nsConfig = new WifiNetworkSelectionConfig.Builder().build();
7875         // no permission to call API
7876         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
7877         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
7878                 .thenReturn(false);
7879         assertThrows(SecurityException.class,
7880                 () -> mWifiServiceImpl.setNetworkSelectionConfig(nsConfig));
7881 
7882         // Null arguments
7883         assertThrows(IllegalArgumentException.class,
7884                 () -> mWifiServiceImpl.setNetworkSelectionConfig(null));
7885 
7886         // has permission to call API
7887         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
7888         mWifiServiceImpl.setNetworkSelectionConfig(nsConfig);
7889         mLooper.dispatchAll();
7890         verify(mWifiConnectivityManager).setNetworkSelectionConfig(nsConfig);
7891         verify(mLastCallerInfoManager).put(
7892                 eq(WifiManager.API_SET_NETWORK_SELECTION_CONFIG),
7893                 anyInt(), anyInt(), anyInt(), any(), eq(true));
7894     }
7895 
7896     @Test
testGetNetworkSelectionConfig_Exceptions()7897     public void testGetNetworkSelectionConfig_Exceptions() {
7898         assumeTrue(SdkLevel.isAtLeastT());
7899         IWifiNetworkSelectionConfigListener listener =
7900                 mock(IWifiNetworkSelectionConfigListener.class);
7901         // null listener ==> IllegalArgumentException
7902         assertThrows(IllegalArgumentException.class,
7903                 () -> mWifiServiceImpl.getNetworkSelectionConfig(null));
7904 
7905         // No permission ==> SecurityException
7906         assertThrows(SecurityException.class,
7907                 () -> mWifiServiceImpl.getNetworkSelectionConfig(listener));
7908     }
7909 
7910     @Test
testGetNetworkSelectionConfig_GoodCase()7911     public void testGetNetworkSelectionConfig_GoodCase() throws Exception {
7912         assumeTrue(SdkLevel.isAtLeastT());
7913         IWifiNetworkSelectionConfigListener listener =
7914                 mock(IWifiNetworkSelectionConfigListener.class);
7915         InOrder inOrder = inOrder(listener);
7916 
7917         int [] defaultRssi2 = {-83, -80, -73, -60};
7918         int [] defaultRssi5 = {-80, -77, -70, -57};
7919         int [] defaultRssi6 = {-80, -77, -70, -57};
7920         int [] customRssi2 = {-80, -70, -60, -50};
7921         int [] customRssi5 = {-80, -75, -70, -65};
7922         int [] customRssi6 = {-75, -70, -65, -60};
7923         int [] resetArray = {0, 0, 0, 0};
7924 
7925         // has permission to call API
7926         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
7927 
7928         // configure the default values for RSSI thresholds from ScoringParams
7929         when(mScoringParams.getRssiArray(ScanResult.BAND_24_GHZ_START_FREQ_MHZ))
7930                 .thenReturn(defaultRssi2);
7931         when(mScoringParams.getRssiArray(ScanResult.BAND_5_GHZ_START_FREQ_MHZ))
7932                 .thenReturn(defaultRssi5);
7933         when(mScoringParams.getRssiArray(ScanResult.BAND_6_GHZ_START_FREQ_MHZ))
7934                 .thenReturn(defaultRssi6);
7935 
7936         // getting the WifiNetworkSelectionConfig when one hasn't been set returns the default one
7937         // built from the builder with RSSI thresholds from ScoringParams
7938         mWifiServiceImpl.getNetworkSelectionConfig(listener);
7939         mLooper.dispatchAll();
7940         WifiNetworkSelectionConfig defaultConfig = new WifiNetworkSelectionConfig.Builder()
7941                 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, defaultRssi2)
7942                 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, defaultRssi5)
7943                 .setRssiThresholds(WIFI_BAND_6_GHZ, defaultRssi6)
7944                 .build();
7945         inOrder.verify(listener).onResult(defaultConfig);
7946 
7947         // set the WifiNetworkSelectionConfig and verify that same config is retrieved
7948         WifiNetworkSelectionConfig customConfig = new WifiNetworkSelectionConfig.Builder()
7949                 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, customRssi2)
7950                 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, customRssi5)
7951                 .setRssiThresholds(WIFI_BAND_6_GHZ, customRssi6)
7952                 .setUserConnectChoiceOverrideEnabled(false)
7953                 .setLastSelectionWeightEnabled(false)
7954                 .build();
7955 
7956         mWifiServiceImpl.setNetworkSelectionConfig(customConfig);
7957         mLooper.dispatchAll();
7958         verify(mWifiConnectivityManager).setNetworkSelectionConfig(customConfig);
7959 
7960         mWifiServiceImpl.getNetworkSelectionConfig(listener);
7961         mLooper.dispatchAll();
7962         inOrder.verify(listener).onResult(customConfig);
7963 
7964         // resetting the RSSI thresholds returns the config with RSSI from ScoringParams
7965         WifiNetworkSelectionConfig resetConfig = new WifiNetworkSelectionConfig.Builder()
7966                 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, resetArray)
7967                 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, resetArray)
7968                 .setRssiThresholds(WIFI_BAND_6_GHZ, defaultRssi6)
7969                 .build();
7970 
7971         WifiNetworkSelectionConfig resetExpectedConfig = new WifiNetworkSelectionConfig.Builder()
7972                 .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, defaultRssi2)
7973                 .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, defaultRssi5)
7974                 .setRssiThresholds(WIFI_BAND_6_GHZ, defaultRssi6)
7975                 .build();
7976 
7977         mWifiServiceImpl.setNetworkSelectionConfig(resetConfig);
7978         mLooper.dispatchAll();
7979         verify(mWifiConnectivityManager).setNetworkSelectionConfig(resetConfig);
7980 
7981         mWifiServiceImpl.getNetworkSelectionConfig(listener);
7982         mLooper.dispatchAll();
7983 
7984         inOrder.verify(listener).onResult(resetExpectedConfig);
7985     }
7986 
7987     @Test
testSetThirdPartyAppEnablingWifiConfirmationDialogEnabled()7988     public void testSetThirdPartyAppEnablingWifiConfirmationDialogEnabled() throws Exception {
7989         boolean enable = true;
7990 
7991         // no permission to call APIs
7992         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
7993         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt()))
7994                 .thenReturn(false);
7995         assertThrows(SecurityException.class, () ->
7996                 mWifiServiceImpl.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(enable));
7997         assertThrows(SecurityException.class,
7998                 () -> mWifiServiceImpl.isThirdPartyAppEnablingWifiConfirmationDialogEnabled());
7999 
8000         // has permission to call APIs
8001         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
8002         mWifiServiceImpl.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(enable);
8003         verify(mWifiSettingsConfigStore).put(
8004                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI), eq(enable));
8005         verify(mWifiSettingsConfigStore).put(
8006                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API), eq(true));
8007         verify(mLastCallerInfoManager).put(
8008                 eq(WifiManager.API_SET_THIRD_PARTY_APPS_ENABLING_WIFI_CONFIRMATION_DIALOG),
8009                 anyInt(), anyInt(), anyInt(), any(), eq(enable));
8010 
8011         // get value before set by API
8012         when(mWifiSettingsConfigStore.get(
8013                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)))
8014                 .thenReturn(false);
8015         when(mResources.getBoolean(
8016                 R.bool.config_showConfirmationDialogForThirdPartyAppsEnablingWifi))
8017                 .thenReturn(false);
8018         assertFalse(mWifiServiceImpl.isThirdPartyAppEnablingWifiConfirmationDialogEnabled());
8019         verify(mWifiSettingsConfigStore, never())
8020                 .get(eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI));
8021 
8022         // get value after set by API
8023         when(mWifiSettingsConfigStore.get(
8024                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API)))
8025                 .thenReturn(true);
8026         when(mWifiSettingsConfigStore.get(eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI)))
8027                 .thenReturn(true);
8028         assertTrue(mWifiServiceImpl.isThirdPartyAppEnablingWifiConfirmationDialogEnabled());
8029         verify(mWifiSettingsConfigStore).get(eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI));
8030         verify(mWifiSettingsConfigStore, times(2)).get(
8031                 eq(SHOW_DIALOG_WHEN_THIRD_PARTY_APPS_ENABLE_WIFI_SET_BY_API));
8032     }
8033 
8034     @Test(expected = SecurityException.class)
testAllowAutojoinGlobalFailureNoPermission()8035     public void testAllowAutojoinGlobalFailureNoPermission() throws Exception {
8036         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
8037         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
8038                 .thenReturn(false);
8039         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), anyString())).thenReturn(false);
8040         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), anyString())).thenReturn(false);
8041         mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras);
8042     }
8043 
8044     @Test
testAllowAutojoinGlobalWithPermission()8045     public void testAllowAutojoinGlobalWithPermission() throws Exception {
8046         // verify allowAutojoinGlobal with MANAGE_WIFI_NETWORK_SELECTION
8047         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
8048         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
8049                 .thenReturn(true);
8050         when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(false);
8051         mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras);
8052         mLooper.dispatchAll();
8053         verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, false);
8054 
8055         // verify allowAutojoinGlobal with NETWORK_SETTINGS
8056         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
8057         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
8058                 .thenReturn(false);
8059         when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(false);
8060         mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras);
8061         mLooper.dispatchAll();
8062         verify(mWifiConnectivityManager, times(2)).setAutoJoinEnabledExternal(true, false);
8063 
8064         // verify allowAutojoinGlobal with device admin
8065         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
8066         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
8067                 .thenReturn(false);
8068         when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(true);
8069         mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mExtras);
8070         mLooper.dispatchAll();
8071         verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, true);
8072     }
8073 
8074     @Test
testAutoJoinGlobalWithAttributionSourceChain()8075     public void testAutoJoinGlobalWithAttributionSourceChain() {
8076         assumeTrue(SdkLevel.isAtLeastS());
8077 
8078         // verify allowAutojoinGlobal with device admin in attribution source chain
8079         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
8080         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
8081                 .thenReturn(true);
8082         when(mWifiPermissionsUtil.isAdmin(anyInt(), anyString())).thenReturn(false);
8083         // mock attribution chain
8084         AttributionSource attributionSource = mock(AttributionSource.class);
8085         mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource);
8086         when(attributionSource.getUid()).thenReturn(TEST_UID);
8087         when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME);
8088         AttributionSource originalCaller = mock(AttributionSource.class);
8089         when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID);
8090         when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER);
8091         when(attributionSource.getNext()).thenReturn(originalCaller);
8092         // mock the original caller to be device admin via the isAdmin check
8093         when(mWifiPermissionsUtil.isAdmin(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER))
8094                 .thenReturn(true);
8095         mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mAttribution);
8096         mLooper.dispatchAll();
8097         verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(true, true);
8098 
8099         // mock the original caller to be not a device admin and then verify again.
8100         when(mWifiPermissionsUtil.isAdmin(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER))
8101                 .thenReturn(false);
8102         mWifiServiceImpl.allowAutojoinGlobal(false, TEST_PACKAGE_NAME, mAttribution);
8103         mLooper.dispatchAll();
8104         verify(mWifiConnectivityManager).setAutoJoinEnabledExternal(false, false);
8105 
8106         // mock the original caller to be device admin via the isLegacyDeviceAdmin check
8107         when(mWifiPermissionsUtil.isLegacyDeviceAdmin(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER))
8108                 .thenReturn(true);
8109         mWifiServiceImpl.allowAutojoinGlobal(true, TEST_PACKAGE_NAME, mAttribution);
8110         mLooper.dispatchAll();
8111         verify(mWifiConnectivityManager, times(2)).setAutoJoinEnabledExternal(true, true);
8112     }
8113 
8114     @Test
testQueryAutojoinGlobal_Exceptions()8115     public void testQueryAutojoinGlobal_Exceptions() {
8116         // good inputs should result in no exceptions.
8117         IBooleanListener listener = mock(IBooleanListener.class);
8118         // null listener ==> IllegalArgumentException
8119         assertThrows(IllegalArgumentException.class,
8120                 () -> mWifiServiceImpl.queryAutojoinGlobal(null));
8121 
8122         // No permission ==> SecurityException
8123         assertThrows(SecurityException.class,
8124                 () -> mWifiServiceImpl.queryAutojoinGlobal(listener));
8125     }
8126 
8127     @Test
testQueryAutojoinGlobal_GoodCase()8128     public void testQueryAutojoinGlobal_GoodCase() throws RemoteException {
8129         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
8130         IBooleanListener listener = mock(IBooleanListener.class);
8131 
8132         InOrder inOrder = inOrder(listener);
8133         when(mWifiConnectivityManager.getAutoJoinEnabledExternal()).thenReturn(true);
8134         mWifiServiceImpl.queryAutojoinGlobal(listener);
8135         mLooper.dispatchAll();
8136         inOrder.verify(listener).onResult(true);
8137 
8138         when(mWifiConnectivityManager.getAutoJoinEnabledExternal()).thenReturn(false);
8139         mWifiServiceImpl.queryAutojoinGlobal(listener);
8140         mLooper.dispatchAll();
8141         inOrder.verify(listener).onResult(false);
8142     }
8143 
8144     @Test(expected = SecurityException.class)
testSetSsidsDoNotBlocklist_NoPermission()8145     public void testSetSsidsDoNotBlocklist_NoPermission() throws Exception {
8146         // by default no permissions are given so the call should fail.
8147         mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME,
8148                 Collections.EMPTY_LIST);
8149     }
8150 
8151     @Test
testSetSsidsDoNotBlocklist_WithPermission()8152     public void testSetSsidsDoNotBlocklist_WithPermission() throws Exception {
8153         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
8154 
8155         // verify setting an empty list
8156         mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME,
8157                 Collections.EMPTY_LIST);
8158         mLooper.dispatchAll();
8159         verify(mWifiBlocklistMonitor).setSsidsAllowlist(Collections.EMPTY_LIST);
8160 
8161         // verify setting a list of valid SSIDs
8162         List<WifiSsid> expectedSsids = new ArrayList<>();
8163         expectedSsids.add(WifiSsid.fromString(TEST_SSID_WITH_QUOTES));
8164         mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME, expectedSsids);
8165         mLooper.dispatchAll();
8166         verify(mWifiBlocklistMonitor).setSsidsAllowlist(expectedSsids);
8167     }
8168 
8169     @Test
testSetSsidsDoNotBlocklist_WithPermissionAndroidT()8170     public void testSetSsidsDoNotBlocklist_WithPermissionAndroidT()
8171             throws Exception {
8172         assumeTrue(SdkLevel.isAtLeastT());
8173         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
8174                 .thenReturn(true);
8175 
8176         List<WifiSsid> expectedSsids = new ArrayList<>();
8177         expectedSsids.add(WifiSsid.fromString(TEST_SSID_WITH_QUOTES));
8178         mWifiServiceImpl.setSsidsAllowlist(TEST_PACKAGE_NAME, expectedSsids);
8179         mLooper.dispatchAll();
8180         verify(mWifiBlocklistMonitor).setSsidsAllowlist(expectedSsids);
8181     }
8182 
8183     @Test
testAllowAutojoinFailureNoNetworkSettingsPermission()8184     public void testAllowAutojoinFailureNoNetworkSettingsPermission() throws Exception {
8185         doThrow(new SecurityException()).when(mContext)
8186                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8187                         eq("WifiService"));
8188         try {
8189             mWifiServiceImpl.allowAutojoin(0, true);
8190             fail("Expected SecurityException");
8191         } catch (SecurityException e) {
8192             // Test succeeded
8193         }
8194     }
8195 
8196     @Test
testAllowAutojoinOnSuggestionNetwork()8197     public void testAllowAutojoinOnSuggestionNetwork() {
8198         WifiConfiguration config = new WifiConfiguration();
8199         config.allowAutojoin = false;
8200         config.fromWifiNetworkSuggestion = true;
8201         when(mWifiConfigManager.getConfiguredNetwork(anyInt())).thenReturn(config);
8202         when(mWifiNetworkSuggestionsManager.allowNetworkSuggestionAutojoin(any(), anyBoolean()))
8203                 .thenReturn(true);
8204         mWifiServiceImpl.allowAutojoin(0, true);
8205         mLooper.dispatchAll();
8206         verify(mWifiConfigManager).getConfiguredNetwork(0);
8207         verify(mWifiNetworkSuggestionsManager).allowNetworkSuggestionAutojoin(any(), anyBoolean());
8208         verify(mWifiConfigManager).allowAutojoin(anyInt(), anyBoolean());
8209         verify(mWifiMetrics).logUserActionEvent(eq(UserActionEvent.EVENT_CONFIGURE_AUTO_CONNECT_ON),
8210                 anyInt());
8211         verify(mLastCallerInfoManager).put(eq(WifiManager.API_ALLOW_AUTOJOIN), anyInt(),
8212                 anyInt(), anyInt(), anyString(), eq(true));
8213     }
8214 
8215     @Test
testAllowAutojoinOnSavedNetwork()8216     public void testAllowAutojoinOnSavedNetwork() {
8217         WifiConfiguration config = new WifiConfiguration();
8218         config.allowAutojoin = false;
8219         config.fromWifiNetworkSuggestion = false;
8220         config.fromWifiNetworkSpecifier = false;
8221         when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config);
8222         mWifiServiceImpl.allowAutojoin(0, true);
8223         mLooper.dispatchAll();
8224         verify(mWifiConfigManager).getConfiguredNetwork(0);
8225         verify(mWifiNetworkSuggestionsManager, never())
8226                 .allowNetworkSuggestionAutojoin(any(), anyBoolean());
8227         verify(mWifiConfigManager).allowAutojoin(anyInt(), anyBoolean());
8228     }
8229 
8230     @Test
testAllowAutojoinOnWifiNetworkSpecifier()8231     public void testAllowAutojoinOnWifiNetworkSpecifier() {
8232         WifiConfiguration config = new WifiConfiguration();
8233         config.fromWifiNetworkSpecifier = true;
8234         when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config);
8235         mWifiServiceImpl.allowAutojoin(0, true);
8236         mLooper.dispatchAll();
8237         verify(mWifiConfigManager).getConfiguredNetwork(0);
8238         verify(mWifiNetworkSuggestionsManager, never())
8239                 .allowNetworkSuggestionAutojoin(config, true);
8240         verify(mWifiConfigManager, never()).allowAutojoin(0, true);
8241     }
8242 
8243     @Test
testAllowAutojoinOnSavedPasspointNetwork()8244     public void testAllowAutojoinOnSavedPasspointNetwork() {
8245         WifiConfiguration config = WifiConfigurationTestUtil.createPasspointNetwork();
8246         when(mWifiConfigManager.getConfiguredNetwork(0)).thenReturn(config);
8247         when(mWifiNetworkSuggestionsManager.allowNetworkSuggestionAutojoin(any(), anyBoolean()))
8248                 .thenReturn(true);
8249         mWifiServiceImpl.allowAutojoin(0, true);
8250         mLooper.dispatchAll();
8251         verify(mWifiConfigManager).getConfiguredNetwork(0);
8252         verify(mWifiNetworkSuggestionsManager, never())
8253                 .allowNetworkSuggestionAutojoin(config, true);
8254         verify(mWifiConfigManager, never()).allowAutojoin(0, true);
8255     }
8256 
8257     /**
8258      * Test that setMacRandomizationSettingPasspointEnabled is protected by NETWORK_SETTINGS
8259      * permission.
8260      */
8261     @Test
testSetMacRandomizationSettingPasspointEnabledFailureNoNetworkSettingsPermission()8262     public void testSetMacRandomizationSettingPasspointEnabledFailureNoNetworkSettingsPermission()
8263             throws Exception {
8264         doThrow(new SecurityException()).when(mContext)
8265                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8266                         eq("WifiService"));
8267         try {
8268             mWifiServiceImpl.setMacRandomizationSettingPasspointEnabled("TEST_FQDN", true);
8269             fail("Expected SecurityException");
8270         } catch (SecurityException e) {
8271             // Test succeeded
8272         }
8273     }
8274 
8275     /**
8276      * Test that setMacRandomizationSettingPasspointEnabled makes the appropriate calls.
8277      */
8278     @Test
testSetMacRandomizationSettingPasspointEnabled()8279     public void testSetMacRandomizationSettingPasspointEnabled() throws Exception {
8280         mWifiServiceImpl.setMacRandomizationSettingPasspointEnabled("TEST_FQDN", true);
8281         mLooper.dispatchAll();
8282         verify(mPasspointManager).enableMacRandomization("TEST_FQDN", true);
8283     }
8284 
8285     /**
8286      * Test that setPasspointMeteredOverride is protected by NETWORK_SETTINGS permission.
8287      */
8288     @Test
testSetPasspointMeteredOverrideFailureNoNetworkSettingsPermission()8289     public void testSetPasspointMeteredOverrideFailureNoNetworkSettingsPermission()
8290             throws Exception {
8291         doThrow(new SecurityException()).when(mContext)
8292                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8293                         eq("WifiService"));
8294         try {
8295             mWifiServiceImpl.setPasspointMeteredOverride("TEST_FQDN", METERED_OVERRIDE_METERED);
8296             fail("Expected SecurityException");
8297         } catch (SecurityException e) {
8298             // Test succeeded
8299         }
8300     }
8301 
8302     /**
8303      * Test that setPasspointMeteredOverride makes the appropriate calls.
8304      */
8305     @Test
testSetPasspointMeteredOverride()8306     public void testSetPasspointMeteredOverride() throws Exception {
8307         mWifiServiceImpl.setPasspointMeteredOverride("TEST_FQDN", METERED_OVERRIDE_METERED);
8308         mLooper.dispatchAll();
8309         verify(mPasspointManager).setMeteredOverride("TEST_FQDN", METERED_OVERRIDE_METERED);
8310     }
8311 
8312     /**
8313      * Test handle boot completed sequence.
8314      */
8315     @Test
testHandleBootCompleted()8316     public void testHandleBootCompleted() throws Exception {
8317         mWifiServiceImpl.handleBootCompleted();
8318         mLooper.dispatchAll();
8319 
8320         verify(mWifiNetworkFactory).register();
8321         verify(mUntrustedWifiNetworkFactory).register();
8322         verify(mOemWifiNetworkFactory).register();
8323         verify(mRestrictedWifiNetworkFactory).register();
8324         verify(mMultiInternetWifiNetworkFactory).register();
8325         verify(mPasspointManager).initializeProvisioner(any());
8326         verify(mWifiP2pConnection).handleBootCompleted();
8327         verify(mWifiCountryCode).registerListener(any(WifiCountryCode.ChangeListener.class));
8328     }
8329 
8330     /**
8331      * Test handle user switch sequence.
8332      */
8333     @Test
testHandleUserSwitch()8334     public void testHandleUserSwitch() throws Exception {
8335         mWifiServiceImpl.handleUserSwitch(5);
8336         mLooper.dispatchAll();
8337         verify(mWifiConfigManager).handleUserSwitch(5);
8338         verify(mWifiNotificationManager).createNotificationChannels();
8339         verify(mWifiNetworkSuggestionsManager).resetNotification();
8340         verify(mWifiCarrierInfoManager).resetNotification();
8341         verify(mOpenNetworkNotifier).clearPendingNotification(false);
8342         verify(mWakeupController).resetNotification();
8343     }
8344 
8345     /**
8346      * Test handle user unlock sequence.
8347      */
8348     @Test
testHandleUserUnlock()8349     public void testHandleUserUnlock() throws Exception {
8350         mWifiServiceImpl.handleUserUnlock(5);
8351         mLooper.dispatchAll();
8352         verify(mWifiConfigManager).handleUserUnlock(5);
8353     }
8354 
8355     /**
8356      * Test handle user stop sequence.
8357      */
8358     @Test
testHandleUserStop()8359     public void testHandleUserStop() throws Exception {
8360         mWifiServiceImpl.handleUserStop(5);
8361         mLooper.dispatchAll();
8362         verify(mWifiConfigManager).handleUserStop(5);
8363     }
8364 
8365     /**
8366      * Test register scan result callback without permission.
8367      */
8368     @Test(expected = SecurityException.class)
testRegisterScanResultCallbackWithMissingPermission()8369     public void testRegisterScanResultCallbackWithMissingPermission() throws Exception {
8370         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
8371                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
8372         mWifiServiceImpl.registerScanResultsCallback(mScanResultsCallback);
8373     }
8374 
8375     /**
8376      * Test unregister scan result callback without permission.
8377      */
8378     @Test(expected = SecurityException.class)
testUnregisterScanResultCallbackWithMissingPermission()8379     public void testUnregisterScanResultCallbackWithMissingPermission() throws Exception {
8380         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
8381                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
8382         mWifiServiceImpl.unregisterScanResultsCallback(mScanResultsCallback);
8383     }
8384 
8385     /**
8386      * Test register scan result callback with illegal argument.
8387      */
8388     @Test(expected = IllegalArgumentException.class)
testRegisterScanResultCallbackWithIllegalArgument()8389     public void testRegisterScanResultCallbackWithIllegalArgument() throws Exception {
8390         mWifiServiceImpl.registerScanResultsCallback(null);
8391     }
8392 
8393     /**
8394      * Test register and unregister callback will go to ScanRequestProxy;
8395      */
8396     @Test
testRegisterUnregisterScanResultCallback()8397     public void testRegisterUnregisterScanResultCallback() throws Exception {
8398         mWifiServiceImpl.registerScanResultsCallback(mScanResultsCallback);
8399         mLooper.dispatchAll();
8400         verify(mScanRequestProxy).registerScanResultsCallback(mScanResultsCallback);
8401         mWifiServiceImpl.unregisterScanResultsCallback(mScanResultsCallback);
8402         mLooper.dispatchAll();
8403         verify(mScanRequestProxy).unregisterScanResultsCallback(mScanResultsCallback);
8404     }
8405 
8406     /**
8407      * Test register callback without ACCESS_WIFI_STATE permission.
8408      */
8409     @Test(expected = SecurityException.class)
testRegisterSuggestionNetworkCallbackWithMissingAccessWifiPermission()8410     public void testRegisterSuggestionNetworkCallbackWithMissingAccessWifiPermission() {
8411         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
8412                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
8413         mWifiServiceImpl.registerSuggestionConnectionStatusListener(
8414                 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
8415     }
8416 
8417     /**
8418      * Test register callback without ACCESS_FINE_LOCATION permission.
8419      */
8420     @Test(expected = SecurityException.class)
testRegisterSuggestionNetworkCallbackWithMissingFinePermission()8421     public void testRegisterSuggestionNetworkCallbackWithMissingFinePermission() {
8422         doNothing().when(mContext).enforceCallingOrSelfPermission(
8423                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
8424         if (SdkLevel.isAtLeastT()) {
8425             doThrow(new SecurityException()).when(mWifiPermissionsUtil)
8426                     .enforceLocationPermissionInManifest(anyInt(), eq(false));
8427         } else {
8428             doThrow(new SecurityException()).when(mWifiPermissionsUtil)
8429                     .enforceLocationPermission(anyString(), anyString(), anyInt());
8430         }
8431         mWifiServiceImpl.registerSuggestionConnectionStatusListener(
8432                 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
8433     }
8434 
8435     /**
8436      * Test register callback without callback
8437      */
8438     @Test(expected = IllegalArgumentException.class)
testRegisterSuggestionNetworkCallbackWithIllegalArgument()8439     public void testRegisterSuggestionNetworkCallbackWithIllegalArgument() {
8440         mWifiServiceImpl.registerSuggestionConnectionStatusListener(null, TEST_PACKAGE_NAME,
8441                 TEST_FEATURE_ID);
8442     }
8443 
8444     /**
8445      * Test unregister callback without permission.
8446      */
8447     @Test(expected = SecurityException.class)
testUnregisterSuggestionNetworkCallbackWithMissingPermission()8448     public void testUnregisterSuggestionNetworkCallbackWithMissingPermission() {
8449         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
8450                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
8451         mWifiServiceImpl.unregisterSuggestionConnectionStatusListener(
8452                 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME);
8453     }
8454 
8455     /**
8456      * Test register nad unregister callback will go to WifiNetworkSuggestionManager
8457      */
8458     @Test
testRegisterUnregisterSuggestionNetworkCallback()8459     public void testRegisterUnregisterSuggestionNetworkCallback() throws Exception {
8460         mWifiServiceImpl.registerSuggestionConnectionStatusListener(
8461                 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
8462         mLooper.dispatchAll();
8463         verify(mWifiNetworkSuggestionsManager).registerSuggestionConnectionStatusListener(
8464                 eq(mSuggestionConnectionStatusListener), eq(TEST_PACKAGE_NAME), anyInt());
8465         mWifiServiceImpl.unregisterSuggestionConnectionStatusListener(
8466                 mSuggestionConnectionStatusListener, TEST_PACKAGE_NAME);
8467         mLooper.dispatchAll();
8468         verify(mWifiNetworkSuggestionsManager).unregisterSuggestionConnectionStatusListener(
8469                 eq(mSuggestionConnectionStatusListener), eq(TEST_PACKAGE_NAME), anyInt());
8470     }
8471 
8472 
8473     /**
8474      * Test to verify that the lock mode is verified before dispatching the operation
8475      *
8476      * Steps: call acquireWifiLock with an invalid lock mode.
8477      * Expected: the call should throw an IllegalArgumentException.
8478      */
8479     @Test(expected = IllegalArgumentException.class)
acquireWifiLockShouldThrowExceptionOnInvalidLockMode()8480     public void acquireWifiLockShouldThrowExceptionOnInvalidLockMode() throws Exception {
8481         final int wifiLockModeInvalid = -1;
8482 
8483         mWifiServiceImpl.acquireWifiLock(mAppBinder, wifiLockModeInvalid, "", null);
8484     }
8485 
setupReportActivityInfo()8486     private void setupReportActivityInfo() {
8487         WifiLinkLayerStats stats = new WifiLinkLayerStats();
8488         stats.on_time = 1000;
8489         stats.tx_time = 1;
8490         stats.rx_time = 2;
8491         stats.tx_time_per_level = new int[] {3, 4, 5};
8492         stats.on_time_scan = 6;
8493         when(mClientModeManager.getWifiLinkLayerStats()).thenReturn(stats);
8494         when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_IDLE))
8495                 .thenReturn(7.0);
8496         when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_RX))
8497                 .thenReturn(8.0);
8498         when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_TX))
8499                 .thenReturn(9.0);
8500         when(mPowerProfile.getAveragePower(PowerProfile.POWER_WIFI_CONTROLLER_OPERATING_VOLTAGE))
8501                 .thenReturn(10000.0);
8502         when(mClock.getElapsedSinceBootMillis()).thenReturn(9999L);
8503     }
8504 
validateWifiActivityEnergyInfo(WifiActivityEnergyInfo info)8505     private void validateWifiActivityEnergyInfo(WifiActivityEnergyInfo info) {
8506         assertNotNull(info);
8507         assertEquals(9999L, info.getTimeSinceBootMillis());
8508         assertEquals(WifiActivityEnergyInfo.STACK_STATE_STATE_IDLE, info.getStackState());
8509         assertEquals(1, info.getControllerTxDurationMillis());
8510         assertEquals(2, info.getControllerRxDurationMillis());
8511         assertEquals(6, info.getControllerScanDurationMillis());
8512         assertEquals(997, info.getControllerIdleDurationMillis());
8513     }
8514 
8515     /**
8516      * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} throws
8517      * {@link SecurityException} if the caller doesn't have the necessary permissions.
8518      */
8519     @Test(expected = SecurityException.class)
getWifiActivityEnergyInfoAsyncNoPermission()8520     public void getWifiActivityEnergyInfoAsyncNoPermission() throws Exception {
8521         doThrow(SecurityException.class)
8522                 .when(mContext).enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), any());
8523         mWifiServiceImpl.getWifiActivityEnergyInfoAsync(mOnWifiActivityEnergyInfoListener);
8524     }
8525 
8526     /**
8527      * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} passes null to the listener
8528      * if link layer stats is unsupported.
8529      */
8530     @Test
getWifiActivityEnergyInfoAsyncFeatureUnsupported()8531     public void getWifiActivityEnergyInfoAsyncFeatureUnsupported() throws Exception {
8532         when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(0L);
8533         mLooper.startAutoDispatch();
8534         mWifiServiceImpl.getWifiActivityEnergyInfoAsync(mOnWifiActivityEnergyInfoListener);
8535         mLooper.stopAutoDispatch();
8536         verify(mOnWifiActivityEnergyInfoListener).onWifiActivityEnergyInfo(null);
8537     }
8538 
8539     /**
8540      * Tests that {@link WifiServiceImpl#getWifiActivityEnergyInfoAsync} passes the expected values
8541      * to the listener on success.
8542      */
8543     @Test
getWifiActivityEnergyInfoAsyncSuccess()8544     public void getWifiActivityEnergyInfoAsyncSuccess() throws Exception {
8545         when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(Long.MAX_VALUE);
8546         setupReportActivityInfo();
8547         mLooper.startAutoDispatch();
8548         mWifiServiceImpl.getWifiActivityEnergyInfoAsync(mOnWifiActivityEnergyInfoListener);
8549         mLooper.stopAutoDispatch();
8550         ArgumentCaptor<WifiActivityEnergyInfo> infoCaptor =
8551                 ArgumentCaptor.forClass(WifiActivityEnergyInfo.class);
8552         verify(mOnWifiActivityEnergyInfoListener).onWifiActivityEnergyInfo(infoCaptor.capture());
8553         validateWifiActivityEnergyInfo(infoCaptor.getValue());
8554     }
8555 
8556     @Test
testCarrierConfigChangeUpdateSoftApCapability()8557     public void testCarrierConfigChangeUpdateSoftApCapability() throws Exception {
8558         lenient().when(SubscriptionManager.getActiveDataSubscriptionId())
8559                 .thenReturn(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
8560         mWifiServiceImpl.checkAndStartWifi();
8561         mLooper.dispatchAll();
8562         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
8563                 argThat((IntentFilter filter) ->
8564                         filter.hasAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)),
8565                 isNull(),
8566                 any(Handler.class));
8567 
8568         // Send the broadcast
8569         Intent intent = new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED);
8570         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
8571         mLooper.dispatchAll();
8572         verify(mActiveModeWarden).updateSoftApCapability(any(),
8573                 eq(WifiManager.IFACE_IP_MODE_TETHERED));
8574     }
8575 
8576     @Test
testPhoneActiveDataSubscriptionIdChangedUpdateSoftApCapability()8577     public void testPhoneActiveDataSubscriptionIdChangedUpdateSoftApCapability() throws Exception {
8578         lenient().when(SubscriptionManager.getActiveDataSubscriptionId())
8579                 .thenReturn(SubscriptionManager.DEFAULT_SUBSCRIPTION_ID);
8580         mWifiServiceImpl.checkAndStartWifi();
8581         mLooper.dispatchAll();
8582         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
8583                 argThat((IntentFilter filter) ->
8584                         filter.hasAction(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)),
8585                 isNull(),
8586                 any(Handler.class));
8587         ArgumentCaptor<PhoneStateListener> phoneStateListenerCaptor =
8588                 ArgumentCaptor.forClass(PhoneStateListener.class);
8589         verify(mTelephonyManager).listen(phoneStateListenerCaptor.capture(),
8590                 eq(PhoneStateListener.LISTEN_ACTIVE_DATA_SUBSCRIPTION_ID_CHANGE));
8591         mPhoneStateListener = phoneStateListenerCaptor.getValue();
8592         assertNotNull(mPhoneStateListener);
8593         mPhoneStateListener.onActiveDataSubscriptionIdChanged(2);
8594         mLooper.dispatchAll();
8595         verify(mActiveModeWarden).updateSoftApCapability(any(),
8596                 eq(WifiManager.IFACE_IP_MODE_TETHERED));
8597     }
8598 
8599     /**
8600      * Verify that the call to getWifiConfigsForMatchedNetworkSuggestions is not redirected to
8601      * specific API getWifiConfigForMatchedNetworkSuggestionsSharedWithUser when the caller doesn't
8602      * have NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD.
8603      */
8604     @Test(expected = SecurityException.class)
testGetWifiConfigsForMatchedNetworkSuggestionsWithoutPermissions()8605     public void testGetWifiConfigsForMatchedNetworkSuggestionsWithoutPermissions() {
8606         mWifiServiceImpl.getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(new ArrayList<>());
8607     }
8608 
8609     /**
8610      * Verify that the call to getWifiConfigsForMatchedNetworkSuggestions is redirected to
8611      * specific API getWifiConfigForMatchedNetworkSuggestionsSharedWithUser when the caller
8612      * have NETWORK_SETTINGS.
8613      */
8614     @Test
testGetWifiConfigsForMatchedNetworkSuggestionsWithSettingPermissions()8615     public void testGetWifiConfigsForMatchedNetworkSuggestionsWithSettingPermissions() {
8616         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8617                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
8618         mLooper.startAutoDispatch();
8619         mWifiServiceImpl
8620                 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(createScanResultList());
8621         mLooper.stopAutoDispatch();
8622         verify(mWifiNetworkSuggestionsManager)
8623                 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(any());
8624     }
8625 
8626     /**
8627      * Verify that the call to getWifiConfigsForMatchedNetworkSuggestions is redirected to
8628      * specific API getWifiConfigForMatchedNetworkSuggestionsSharedWithUser when the caller
8629      * have NETWORK_SETUP_WIZARD.
8630      */
8631     @Test
testGetWifiConfigsForMatchedNetworkSuggestionsWithSetupWizardPermissions()8632     public void testGetWifiConfigsForMatchedNetworkSuggestionsWithSetupWizardPermissions() {
8633         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
8634                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
8635         mLooper.startAutoDispatch();
8636         mWifiServiceImpl
8637                 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(createScanResultList());
8638         mLooper.stopAutoDispatch();
8639         verify(mWifiNetworkSuggestionsManager)
8640                 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(any());
8641     }
8642 
8643     @Test
testGetWifiConfigsForMatchedNetworkSuggestionsWithInvalidScanResults()8644     public void testGetWifiConfigsForMatchedNetworkSuggestionsWithInvalidScanResults() {
8645         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8646                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
8647         mWifiServiceImpl
8648                 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(new ArrayList<>());
8649         mLooper.dispatchAll();
8650         verify(mWifiNetworkSuggestionsManager, never())
8651                 .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(any());
8652     }
8653 
8654     /**
8655      * Verify that a call to setWifiConnectedNetworkScorer throws a SecurityException if
8656      * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission.
8657      */
8658     @Test
testSetNetworkScorerThrowsSecurityExceptionOnMissingPermissions()8659     public void testSetNetworkScorerThrowsSecurityExceptionOnMissingPermissions() {
8660         doThrow(new SecurityException()).when(mContext)
8661                 .enforceCallingOrSelfPermission(
8662                         eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE),
8663                         eq("WifiService"));
8664         try {
8665             mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, mWifiConnectedNetworkScorer);
8666             fail("expected SecurityException");
8667         } catch (SecurityException expected) {
8668         }
8669     }
8670 
8671     /**
8672      * Verify that a call to setWifiConnectedNetworkScorer throws an IllegalArgumentException
8673      * if the parameters are not provided.
8674      */
8675     @Test
testSetScorerThrowsIllegalArgumentExceptionOnInvalidArguments()8676     public void testSetScorerThrowsIllegalArgumentExceptionOnInvalidArguments() {
8677         try {
8678             mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, null);
8679             fail("expected IllegalArgumentException");
8680         } catch (IllegalArgumentException expected) {
8681         }
8682     }
8683 
8684     /**
8685      * Verify that a call to clearWifiConnectedNetworkScorer throws a SecurityException if
8686      * the caller does not have WIFI_UPDATE_USABILITY_STATS_SCORE permission.
8687      */
8688     @Test
testClearNetworkScorerThrowsSecurityExceptionOnMissingPermissions()8689     public void testClearNetworkScorerThrowsSecurityExceptionOnMissingPermissions() {
8690         doThrow(new SecurityException()).when(mContext)
8691                 .enforceCallingOrSelfPermission(
8692                         eq(android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE),
8693                                 eq("WifiService"));
8694         try {
8695             mWifiServiceImpl.clearWifiConnectedNetworkScorer();
8696             fail("expected SecurityException");
8697         } catch (SecurityException expected) {
8698         }
8699     }
8700 
8701     /**
8702      * Verify that setWifiConnectedNetworkScorer sets scorer to {@link WifiScoreReport}.
8703      */
8704     @Test
testSetWifiConnectedNetworkScorerAndVerify()8705     public void testSetWifiConnectedNetworkScorerAndVerify() throws Exception {
8706         mLooper.startAutoDispatch();
8707         mWifiServiceImpl.setWifiConnectedNetworkScorer(mAppBinder, mWifiConnectedNetworkScorer);
8708         mLooper.stopAutoDispatch();
8709         verify(mActiveModeWarden).setWifiConnectedNetworkScorer(
8710                 mAppBinder, mWifiConnectedNetworkScorer);
8711     }
8712 
8713     /**
8714      * Verify that clearWifiConnectedNetworkScorer clears scorer from {@link WifiScoreReport}.
8715      */
8716     @Test
testClearWifiConnectedNetworkScorerAndVerify()8717     public void testClearWifiConnectedNetworkScorerAndVerify() throws Exception {
8718         mWifiServiceImpl.clearWifiConnectedNetworkScorer();
8719         mLooper.dispatchAll();
8720         verify(mActiveModeWarden).clearWifiConnectedNetworkScorer();
8721     }
8722 
8723     /**
8724      * Verify that a call to addWifiCustomDhcpOptions throws a SecurityException if
8725      * the caller does not have NETWORK_SETTINGS or OVERRIDE_WIFI_CONFIG permission.
8726      */
8727     @Test
testAddCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions()8728     public void testAddCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions() {
8729         assumeTrue(SdkLevel.isAtLeastT());
8730         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS))
8731                 .thenReturn(PackageManager.PERMISSION_DENIED);
8732         when(mContext.checkCallingOrSelfPermission(
8733                 android.Manifest.permission.OVERRIDE_WIFI_CONFIG))
8734                 .thenReturn(PackageManager.PERMISSION_DENIED);
8735         try {
8736             mWifiServiceImpl.addCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES),
8737                     TEST_OUI, new ArrayList<DhcpOption>());
8738             fail("expected SecurityException");
8739         } catch (SecurityException expected) {
8740         }
8741     }
8742 
8743     /**
8744      * Verify that a call to removeWifiCustomDhcpOptions throws a SecurityException if
8745      * the caller does not have NETWORK_SETTINGS or OVERRIDE_WIFI_CONFIG permission.
8746      */
8747     @Test
testRemoveCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions()8748     public void testRemoveCustomDhcpOptionsThrowsSecurityExceptionOnMissingPermissions() {
8749         assumeTrue(SdkLevel.isAtLeastT());
8750         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS))
8751                 .thenReturn(PackageManager.PERMISSION_DENIED);
8752         when(mContext.checkCallingOrSelfPermission(
8753                 android.Manifest.permission.OVERRIDE_WIFI_CONFIG))
8754                 .thenReturn(PackageManager.PERMISSION_DENIED);
8755         try {
8756             mWifiServiceImpl.removeCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES),
8757                     TEST_OUI);
8758             fail("expected SecurityException");
8759         } catch (SecurityException expected) {
8760         }
8761     }
8762 
8763     /**
8764      * Verify that addWifiCustomDhcpOptions adds DHCP option.
8765      */
8766     @Test
testAddCustomDhcpOptionsAndVerify()8767     public void testAddCustomDhcpOptionsAndVerify() throws Exception {
8768         assumeTrue(SdkLevel.isAtLeastT());
8769         mWifiServiceImpl.addCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_OUI,
8770                 new ArrayList<DhcpOption>());
8771         mLooper.dispatchAll();
8772         verify(mWifiConfigManager).addCustomDhcpOptions(
8773                 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_OUI, new ArrayList<DhcpOption>());
8774     }
8775 
8776     /**
8777      * Verify that removeWifiCustomDhcpOptions removes DHCP option.
8778      */
8779     @Test
testRemoveCustomDhcpOptionsAndVerify()8780     public void testRemoveCustomDhcpOptionsAndVerify() throws Exception {
8781         assumeTrue(SdkLevel.isAtLeastT());
8782         mWifiServiceImpl.removeCustomDhcpOptions(WifiSsid.fromString(TEST_SSID_WITH_QUOTES),
8783                 TEST_OUI);
8784         mLooper.dispatchAll();
8785         verify(mWifiConfigManager).removeCustomDhcpOptions(
8786                 WifiSsid.fromString(TEST_SSID_WITH_QUOTES), TEST_OUI);
8787     }
8788 
8789     @Test
getSupportedFeaturesVerboseLoggingThrottled()8790     public void getSupportedFeaturesVerboseLoggingThrottled() {
8791         mWifiServiceImpl.enableVerboseLogging(
8792                 WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED); // this logs
8793         when(mClock.getElapsedSinceBootMillis()).thenReturn(1000L);
8794         when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(0x110L);
8795         mWifiServiceImpl.getSupportedFeatures();
8796         when(mClock.getElapsedSinceBootMillis()).thenReturn(1001L);
8797         mWifiServiceImpl.getSupportedFeatures(); // should not log
8798         when(mClock.getElapsedSinceBootMillis()).thenReturn(5000L);
8799         mWifiServiceImpl.getSupportedFeatures();
8800         when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(0x100L);
8801         mWifiServiceImpl.getSupportedFeatures();
8802         verify(mLog, times(4)).info(any());
8803     }
8804 
8805     /**
8806      * Verify startRestrictingAutoJoinToSubscriptionId is guarded by NETWORK_SETTINGS
8807      * permission.
8808      */
8809     @Test
testStartTemporarilyDisablingAllNonCarrierMergedWifiPermission()8810     public void testStartTemporarilyDisablingAllNonCarrierMergedWifiPermission() {
8811         assumeTrue(SdkLevel.isAtLeastS());
8812         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8813                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
8814         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
8815                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
8816         try {
8817             mWifiServiceImpl.startRestrictingAutoJoinToSubscriptionId(1);
8818             fail();
8819         } catch (SecurityException e) {
8820             // pass
8821         }
8822     }
8823 
8824     /**
8825      * Verify startRestrictingAutoJoinToSubscriptionId works properly with permission.
8826      */
8827     @Test
testStartTemporarilyDisablingAllNonCarrierMergedWifi()8828     public void testStartTemporarilyDisablingAllNonCarrierMergedWifi() {
8829         assumeTrue(SdkLevel.isAtLeastS());
8830         List<ClientModeManager> cmmList = new ArrayList<>();
8831         ConcreteClientModeManager localOnlyCmm = mock(ConcreteClientModeManager.class);
8832         ConcreteClientModeManager secondaryTransientCmm = mock(ConcreteClientModeManager.class);
8833         when(localOnlyCmm.getRole()).thenReturn(ROLE_CLIENT_LOCAL_ONLY);
8834         when(secondaryTransientCmm.getRole()).thenReturn(ROLE_CLIENT_SECONDARY_TRANSIENT);
8835         cmmList.add(mClientModeManager);
8836         cmmList.add(localOnlyCmm);
8837         cmmList.add(secondaryTransientCmm);
8838         when(mActiveModeWarden.getClientModeManagers()).thenReturn(cmmList);
8839         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
8840                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
8841 
8842         mWifiServiceImpl.startRestrictingAutoJoinToSubscriptionId(1);
8843         mLooper.dispatchAll();
8844         verify(mWifiConfigManager).startRestrictingAutoJoinToSubscriptionId(1);
8845         verify(mWifiConnectivityManager).clearCachedCandidates();
8846         verify(localOnlyCmm, never()).disconnect();
8847         verify(secondaryTransientCmm).disconnect();
8848         verify(mClientModeManager).disconnect();
8849     }
8850 
8851     /**
8852      * Verify stopRestrictingAutoJoinToSubscriptionId is guarded by NETWORK_SETTINGS
8853      * and NETWORK_SETUP_WIZARD permission.
8854      */
8855     @Test
testStopTemporarilyDisablingAllNonCarrierMergedWifiPermission()8856     public void testStopTemporarilyDisablingAllNonCarrierMergedWifiPermission() {
8857         assumeTrue(SdkLevel.isAtLeastS());
8858         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8859                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
8860         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
8861                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_DENIED);
8862         try {
8863             mWifiServiceImpl.stopRestrictingAutoJoinToSubscriptionId();
8864             fail();
8865         } catch (SecurityException e) {
8866             // pass
8867         }
8868     }
8869 
8870     /**
8871      * Verify stopRestrictingAutoJoinToSubscriptionId works properly with permission.
8872      */
8873     @Test
testStopTemporarilyDisablingAllNonCarrierMergedWifi()8874     public void testStopTemporarilyDisablingAllNonCarrierMergedWifi() {
8875         assumeTrue(SdkLevel.isAtLeastS());
8876         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8877                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
8878         mWifiServiceImpl.stopRestrictingAutoJoinToSubscriptionId();
8879         mLooper.dispatchAll();
8880         verify(mWifiConfigManager).stopRestrictingAutoJoinToSubscriptionId();
8881     }
8882 
8883     @Test(expected = SecurityException.class)
testGetCountryCodeThrowsException()8884     public void testGetCountryCodeThrowsException() {
8885         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
8886         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
8887                 any(), any(), anyInt(), any())).thenReturn(false);
8888         mWifiServiceImpl.getCountryCode(TEST_PACKAGE_NAME, TEST_FEATURE_ID);
8889     }
8890 
8891     @Test
testGetCountryCode()8892     public void testGetCountryCode() {
8893         // verify get country code with network settings permission.
8894         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
8895         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
8896                 any(), any(), anyInt(), any())).thenReturn(false);
8897         mWifiServiceImpl.getCountryCode(TEST_PACKAGE_NAME, TEST_FEATURE_ID);
8898 
8899         // verify get country code with coarse location permission.
8900         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
8901         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
8902                 any(), any(), anyInt(), any())).thenReturn(true);
8903         mWifiServiceImpl.getCountryCode(TEST_PACKAGE_NAME, TEST_FEATURE_ID);
8904     }
8905 
8906     @Test
testSetScanThrottleEnabledWithNetworkSettingsPermission()8907     public void testSetScanThrottleEnabledWithNetworkSettingsPermission() {
8908         doNothing().when(mContext)
8909                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8910                         eq("WifiService"));
8911         mWifiServiceImpl.setScanThrottleEnabled(true);
8912         verify(mScanRequestProxy).setScanThrottleEnabled(true);
8913 
8914         mWifiServiceImpl.setScanThrottleEnabled(false);
8915         verify(mScanRequestProxy).setScanThrottleEnabled(false);
8916     }
8917 
8918     @Test(expected = SecurityException.class)
testSetScanThrottleEnabledWithNoNetworkSettingsPermission()8919     public void testSetScanThrottleEnabledWithNoNetworkSettingsPermission() {
8920         doThrow(new SecurityException()).when(mContext)
8921                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8922                         eq("WifiService"));
8923 
8924         mWifiServiceImpl.setScanThrottleEnabled(true);
8925         verify(mScanRequestProxy, never()).setScanThrottleEnabled(true);
8926     }
8927 
8928     @Test
testIsScanThrottleEnabled()8929     public void testIsScanThrottleEnabled() {
8930         when(mScanRequestProxy.isScanThrottleEnabled()).thenReturn(true);
8931         assertTrue(mWifiServiceImpl.isScanThrottleEnabled());
8932         verify(mScanRequestProxy).isScanThrottleEnabled();
8933     }
8934 
8935     @Test
testSetAutoWakeupEnabledWithNetworkSettingsPermission()8936     public void testSetAutoWakeupEnabledWithNetworkSettingsPermission() {
8937         doNothing().when(mContext)
8938                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8939                         eq("WifiService"));
8940         mWifiServiceImpl.setAutoWakeupEnabled(true);
8941         verify(mWakeupController).setEnabled(true);
8942 
8943         mWifiServiceImpl.setAutoWakeupEnabled(false);
8944         verify(mWakeupController).setEnabled(false);
8945     }
8946 
8947     @Test(expected = SecurityException.class)
testSetAutoWakeupEnabledWithNoNetworkSettingsPermission()8948     public void testSetAutoWakeupEnabledWithNoNetworkSettingsPermission() {
8949         doThrow(new SecurityException()).when(mContext)
8950                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8951                         eq("WifiService"));
8952 
8953         mWifiServiceImpl.setAutoWakeupEnabled(true);
8954         mLooper.dispatchAll();
8955         verify(mWakeupController, never()).setEnabled(true);
8956     }
8957 
8958     @Test
testIsAutoWakeupEnabled()8959     public void testIsAutoWakeupEnabled() {
8960         when(mWakeupController.isEnabled()).thenReturn(true);
8961         assertTrue(mWifiServiceImpl.isAutoWakeupEnabled());
8962         verify(mWakeupController).isEnabled();
8963     }
8964 
8965     @Test
testSetScanAlwaysAvailableWithNetworkSettingsPermission()8966     public void testSetScanAlwaysAvailableWithNetworkSettingsPermission() {
8967         doNothing().when(mContext)
8968                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8969                         eq("WifiService"));
8970         mWifiServiceImpl.setScanAlwaysAvailable(true, TEST_PACKAGE_NAME);
8971         verify(mSettingsStore).handleWifiScanAlwaysAvailableToggled(true);
8972         verify(mActiveModeWarden).scanAlwaysModeChanged();
8973 
8974         mWifiServiceImpl.setScanAlwaysAvailable(false, TEST_PACKAGE_NAME);
8975         verify(mSettingsStore).handleWifiScanAlwaysAvailableToggled(false);
8976         verify(mActiveModeWarden, times(2)).scanAlwaysModeChanged();
8977     }
8978 
8979     @Test(expected = SecurityException.class)
testSetScanAlwaysAvailableWithNoNetworkSettingsPermission()8980     public void testSetScanAlwaysAvailableWithNoNetworkSettingsPermission() {
8981         doThrow(new SecurityException()).when(mContext)
8982                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
8983                         eq("WifiService"));
8984 
8985         mWifiServiceImpl.setScanAlwaysAvailable(true, TEST_PACKAGE_NAME);
8986         verify(mSettingsStore, never()).handleWifiScanAlwaysAvailableToggled(anyBoolean());
8987         verify(mActiveModeWarden, never()).scanAlwaysModeChanged();
8988     }
8989 
8990     @Test
testIsScanAlwaysAvailable()8991     public void testIsScanAlwaysAvailable() {
8992         when(mSettingsStore.isScanAlwaysAvailableToggleEnabled()).thenReturn(true);
8993         assertTrue(mWifiServiceImpl.isScanAlwaysAvailable());
8994         verify(mSettingsStore).isScanAlwaysAvailableToggleEnabled();
8995     }
8996 
createScanResultList()8997     private List<ScanResult> createScanResultList() {
8998         return Collections.singletonList(new ScanResult(WifiSsid.fromUtf8Text(TEST_SSID),
8999                 TEST_SSID, TEST_BSSID, 1245, 0, TEST_CAP, -78, 2450, 1025, 22, 33, 20, 0, 0, true));
9000     }
9001 
sendCountryCodeChangedBroadcast(String countryCode)9002     private void sendCountryCodeChangedBroadcast(String countryCode) {
9003         Intent intent = new Intent(TelephonyManager.ACTION_NETWORK_COUNTRY_CHANGED);
9004         intent.putExtra(TelephonyManager.EXTRA_NETWORK_COUNTRY, countryCode);
9005         assertNotNull(mBroadcastReceiverCaptor.getValue());
9006         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
9007     }
9008 
9009     @Test
testCountryCodeBroadcastHanding()9010     public void testCountryCodeBroadcastHanding() {
9011         mWifiServiceImpl.checkAndStartWifi();
9012         mLooper.dispatchAll();
9013         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
9014                 argThat((IntentFilter filter) ->
9015                         filter.hasAction(TelephonyManager.ACTION_NETWORK_COUNTRY_CHANGED)),
9016                 isNull(),
9017                 any(Handler.class));
9018         sendCountryCodeChangedBroadcast("US");
9019         verify(mWifiCountryCode).setTelephonyCountryCodeAndUpdate(any());
9020     }
9021 
9022     @Test
testDumpShouldDumpWakeupController()9023     public void testDumpShouldDumpWakeupController() {
9024         mWifiServiceImpl.checkAndStartWifi();
9025         mLooper.dispatchAll();
9026         mWifiServiceImpl.dump(new FileDescriptor(), new PrintWriter(new StringWriter()), null);
9027         mLooper.dispatchAll();
9028         verify(mWakeupController).dump(any(), any(), any());
9029     }
9030 
9031     /**
9032      * Test register listener without permission.
9033      */
9034     @Test(expected = SecurityException.class)
testAddSuggestionUserApprovalStatusListenerWithMissingPermission()9035     public void testAddSuggestionUserApprovalStatusListenerWithMissingPermission() {
9036         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
9037                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
9038         mWifiServiceImpl.addSuggestionUserApprovalStatusListener(
9039                 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME);
9040     }
9041 
9042     /**
9043      * Test register listener from background user.
9044      */
9045     @Test(expected = SecurityException.class)
testAddSuggestionUserApprovalStatusListenerFromBackgroundUser()9046     public void testAddSuggestionUserApprovalStatusListenerFromBackgroundUser() {
9047         when(mWifiPermissionsUtil.doesUidBelongToCurrentUserOrDeviceOwner(anyInt()))
9048                 .thenReturn(false);
9049         mWifiServiceImpl.addSuggestionUserApprovalStatusListener(
9050                 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME);
9051     }
9052 
9053     /**
9054      * Test unregister listener from background user.
9055      */
9056     @Test(expected = SecurityException.class)
testRemoveSuggestionUserApprovalStatusListenerFromBackgroundUser()9057     public void testRemoveSuggestionUserApprovalStatusListenerFromBackgroundUser() {
9058         when(mWifiPermissionsUtil.doesUidBelongToCurrentUserOrDeviceOwner(anyInt()))
9059                 .thenReturn(false);
9060         mWifiServiceImpl.removeSuggestionUserApprovalStatusListener(
9061                 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME);
9062     }
9063 
9064     /**
9065      * Test register listener without listener
9066      */
9067     @Test(expected = NullPointerException.class)
testAddSuggestionUserApprovalStatusListenerWithIllegalArgument()9068     public void testAddSuggestionUserApprovalStatusListenerWithIllegalArgument() {
9069         mWifiServiceImpl.addSuggestionUserApprovalStatusListener(null, TEST_PACKAGE_NAME);
9070     }
9071 
9072     /**
9073      * Test unregister callback without permission.
9074      */
9075     @Test(expected = SecurityException.class)
testUnregisterSuggestionUserApprovalStatusListenerWithMissingPermission()9076     public void testUnregisterSuggestionUserApprovalStatusListenerWithMissingPermission() {
9077         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
9078                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
9079         mWifiServiceImpl.removeSuggestionUserApprovalStatusListener(
9080                 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME);
9081     }
9082 
9083     /**
9084      * Test add and remove listener will go to WifiNetworkSuggestionManager
9085      */
9086     @Test
testAddRemoveSuggestionUserApprovalStatusListener()9087     public void testAddRemoveSuggestionUserApprovalStatusListener() {
9088         mWifiServiceImpl.addSuggestionUserApprovalStatusListener(
9089                 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME);
9090         mLooper.dispatchAll();
9091         verify(mWifiNetworkSuggestionsManager).addSuggestionUserApprovalStatusListener(
9092                 eq(mSuggestionUserApprovalStatusListener), eq(TEST_PACKAGE_NAME), anyInt());
9093 
9094         mWifiServiceImpl.removeSuggestionUserApprovalStatusListener(
9095                 mSuggestionUserApprovalStatusListener, TEST_PACKAGE_NAME);
9096         mLooper.dispatchAll();
9097         verify(mWifiNetworkSuggestionsManager).removeSuggestionUserApprovalStatusListener(
9098                 eq(mSuggestionUserApprovalStatusListener), eq(TEST_PACKAGE_NAME), anyInt());
9099     }
9100 
9101     @Test
testGetDhcpInfo()9102     public void testGetDhcpInfo() throws Exception {
9103         DhcpResultsParcelable dhcpResultsParcelable = new DhcpResultsParcelable();
9104         dhcpResultsParcelable.leaseDuration = 100;
9105         when(mClientModeManager.syncGetDhcpResultsParcelable()).thenReturn(dhcpResultsParcelable);
9106 
9107         mLooper.startAutoDispatch();
9108         DhcpInfo dhcpInfo = mWifiServiceImpl.getDhcpInfo(TEST_PACKAGE);
9109         mLooper.stopAutoDispatchAndIgnoreExceptions();
9110 
9111         assertEquals(dhcpResultsParcelable.leaseDuration, dhcpInfo.leaseDuration);
9112     }
9113 
9114     @Test
testGetDhcpInfoFromSecondaryCmmFromAppRequestingSecondaryCmm()9115     public void testGetDhcpInfoFromSecondaryCmmFromAppRequestingSecondaryCmm() throws Exception {
9116         DhcpResultsParcelable dhcpResultsParcelable = new DhcpResultsParcelable();
9117         dhcpResultsParcelable.leaseDuration = 100;
9118         ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class);
9119         when(secondaryCmm.getRequestorWs())
9120                 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE));
9121         when(secondaryCmm.syncGetDhcpResultsParcelable()).thenReturn(dhcpResultsParcelable);
9122         when(mActiveModeWarden.getClientModeManagersInRoles(
9123                 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED))
9124                 .thenReturn(Arrays.asList(secondaryCmm));
9125 
9126         mLooper.startAutoDispatch();
9127         DhcpInfo dhcpInfo = mWifiServiceImpl.getDhcpInfo(TEST_PACKAGE);
9128         mLooper.stopAutoDispatchAndIgnoreExceptions();
9129 
9130         assertEquals(dhcpResultsParcelable.leaseDuration, dhcpInfo.leaseDuration);
9131     }
9132 
9133     @Test
testGetDhcpInfoFromPrimaryCmmFromAppNotRequestingSecondaryCmm()9134     public void testGetDhcpInfoFromPrimaryCmmFromAppNotRequestingSecondaryCmm() throws Exception {
9135         DhcpResultsParcelable dhcpResultsParcelable = new DhcpResultsParcelable();
9136         dhcpResultsParcelable.leaseDuration = 100;
9137         when(mClientModeManager.syncGetDhcpResultsParcelable()).thenReturn(dhcpResultsParcelable);
9138         ConcreteClientModeManager secondaryCmm = mock(ConcreteClientModeManager.class);
9139         when(secondaryCmm.getRequestorWs())
9140                 .thenReturn(new WorkSource(Binder.getCallingUid(), TEST_PACKAGE_NAME_OTHER));
9141         when(mActiveModeWarden.getClientModeManagersInRoles(
9142                 ROLE_CLIENT_LOCAL_ONLY, ROLE_CLIENT_SECONDARY_LONG_LIVED))
9143                 .thenReturn(Arrays.asList(secondaryCmm));
9144 
9145         mLooper.startAutoDispatch();
9146         DhcpInfo dhcpInfo = mWifiServiceImpl.getDhcpInfo(TEST_PACKAGE);
9147         mLooper.stopAutoDispatchAndIgnoreExceptions();
9148 
9149         assertEquals(dhcpResultsParcelable.leaseDuration, dhcpInfo.leaseDuration);
9150     }
9151 
9152     @Test
testSetEmergencyScanRequestInProgress()9153     public void testSetEmergencyScanRequestInProgress() throws Exception {
9154         mWifiServiceImpl.setEmergencyScanRequestInProgress(true);
9155         verify(mActiveModeWarden).setEmergencyScanRequestInProgress(true);
9156 
9157         mWifiServiceImpl.setEmergencyScanRequestInProgress(false);
9158         verify(mActiveModeWarden).setEmergencyScanRequestInProgress(false);
9159     }
9160 
9161     @Test
testSetCarrierNetworkOffloadEnabledWithoutPermissionThrowsException()9162     public void testSetCarrierNetworkOffloadEnabledWithoutPermissionThrowsException()
9163             throws Exception {
9164         try {
9165             mWifiServiceImpl.setCarrierNetworkOffloadEnabled(10, true, true);
9166             fail();
9167         } catch (SecurityException e) { }
9168     }
9169 
9170     @Test
testSetCarrierNetworkOffloadEnabled()9171     public void testSetCarrierNetworkOffloadEnabled() throws Exception {
9172         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
9173                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
9174         mWifiServiceImpl.setCarrierNetworkOffloadEnabled(10, true, true);
9175         verify(mWifiCarrierInfoManager).setCarrierNetworkOffloadEnabled(10, true, true);
9176 
9177         mWifiServiceImpl.setCarrierNetworkOffloadEnabled(5, false, false);
9178         verify(mWifiCarrierInfoManager).setCarrierNetworkOffloadEnabled(5, false, false);
9179     }
9180 
9181     @Test
testIsCarrierNetworkOffloadEnabled()9182     public void testIsCarrierNetworkOffloadEnabled() throws Exception {
9183         when(mWifiCarrierInfoManager.isCarrierNetworkOffloadEnabled(10, true)).thenReturn(true);
9184         assertTrue(mWifiServiceImpl.isCarrierNetworkOffloadEnabled(10, true));
9185         verify(mWifiCarrierInfoManager).isCarrierNetworkOffloadEnabled(10, true);
9186     }
9187 
9188     @Test
testSetEmergencyScanRequestWithoutPermissionThrowsException()9189     public void testSetEmergencyScanRequestWithoutPermissionThrowsException() throws Exception {
9190         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_STACK))
9191                 .thenReturn(PackageManager.PERMISSION_DENIED);
9192         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
9193                 eq(NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK), any());
9194         try {
9195             mWifiServiceImpl.setEmergencyScanRequestInProgress(true);
9196             fail();
9197         } catch (SecurityException e) { }
9198     }
9199 
9200     @Test
testRemoveAppState()9201     public void testRemoveAppState() throws Exception {
9202         mWifiServiceImpl.removeAppState(TEST_UID, TEST_PACKAGE_NAME);
9203         mLooper.dispatchAll();
9204 
9205         verify(mScanRequestProxy).clearScanRequestTimestampsForApp(TEST_PACKAGE_NAME, TEST_UID);
9206         verify(mWifiNetworkSuggestionsManager).removeApp(TEST_PACKAGE_NAME);
9207         verify(mWifiNetworkFactory).removeApp(TEST_PACKAGE_NAME);
9208         verify(mPasspointManager).removePasspointProviderWithPackage(TEST_PACKAGE_NAME);
9209     }
9210 
9211     @Test
testRemoveAppStateWithoutPermissionThrowsException()9212     public void testRemoveAppStateWithoutPermissionThrowsException() throws Exception {
9213         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
9214                 eq(Manifest.permission.NETWORK_SETTINGS), any());
9215         try {
9216             mWifiServiceImpl.removeAppState(TEST_UID, TEST_PACKAGE_NAME);
9217             fail();
9218         } catch (SecurityException e) { }
9219     }
9220 
9221     @Test
testNotificationResetWithLocaleChange()9222     public void testNotificationResetWithLocaleChange() {
9223         mWifiServiceImpl.checkAndStartWifi();
9224         mLooper.dispatchAll();
9225         verify(mContext).registerReceiver(mBroadcastReceiverCaptor.capture(),
9226                 argThat((IntentFilter filter) ->
9227                         filter.hasAction(Intent.ACTION_LOCALE_CHANGED)),
9228                 isNull(),
9229                 any(Handler.class));
9230         verify(mWifiNotificationManager).createNotificationChannels();
9231         clearInvocations(mWifiNotificationManager);
9232 
9233         Intent intent = new Intent(Intent.ACTION_LOCALE_CHANGED);
9234         mBroadcastReceiverCaptor.getValue().onReceive(mContext, intent);
9235         verify(mWifiNotificationManager).createNotificationChannels();
9236         verify(mWifiNetworkSuggestionsManager).resetNotification();
9237         verify(mWifiCarrierInfoManager).resetNotification();
9238         verify(mOpenNetworkNotifier).clearPendingNotification(false);
9239         verify(mWakeupController).resetNotification();
9240     }
9241 
9242     /**
9243      * Verify that a call to setWifiScoringEnabled throws a SecurityException if the caller does
9244      * not have NETWORK_SETTINGS permission.
9245      */
9246     @Test
testSetWifiScoringEnabledThrowsSecurityExceptionOnMissingPermissions()9247     public void testSetWifiScoringEnabledThrowsSecurityExceptionOnMissingPermissions() {
9248         doThrow(new SecurityException()).when(mContext)
9249                 .enforceCallingOrSelfPermission(
9250                 eq(android.Manifest.permission.NETWORK_SETTINGS),
9251                 eq("WifiService"));
9252         try {
9253             mWifiServiceImpl.setWifiScoringEnabled(true);
9254             fail("expected SecurityException");
9255         } catch (SecurityException expected) {
9256         }
9257     }
9258 
9259     /**
9260      * Verify that setWifiScoringEnabled sets the boolean to {@link WifiSettingsStore}.
9261      */
9262     @Test
testSetWifiScoringEnabledGoesToSettingsStore()9263     public void testSetWifiScoringEnabledGoesToSettingsStore() {
9264         mLooper.startAutoDispatch();
9265         mWifiServiceImpl.setWifiScoringEnabled(true);
9266         mLooper.stopAutoDispatch();
9267         verify(mSettingsStore).handleWifiScoringEnabled(true);
9268     }
9269 
9270     @Test
testEnabledTdlsWithMacAddress()9271     public void testEnabledTdlsWithMacAddress() {
9272         mWifiServiceImpl.enableTdlsWithMacAddress(TEST_BSSID, true);
9273         mLooper.dispatchAll();
9274         verify(mClientModeManager).enableTdls(TEST_BSSID, true);
9275 
9276         mWifiServiceImpl.enableTdlsWithMacAddress(TEST_BSSID, false);
9277         mLooper.dispatchAll();
9278         verify(mClientModeManager).enableTdls(TEST_BSSID, false);
9279         verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_TDLS_ENABLED_WITH_MAC_ADDRESS),
9280                 anyInt(), anyInt(), anyInt(), anyString(), eq(false));
9281     }
9282 
9283     @Test
testEnabledTdlsWithMacAddressCallback()9284     public void testEnabledTdlsWithMacAddressCallback() throws RemoteException {
9285         IBooleanListener listener = mock(IBooleanListener.class);
9286         InOrder inOrder = inOrder(listener);
9287 
9288         when(mClientModeManager.enableTdls(TEST_BSSID, true)).thenReturn(true);
9289         mWifiServiceImpl.enableTdlsWithRemoteMacAddress(TEST_BSSID, true, listener);
9290         mLooper.dispatchAll();
9291         inOrder.verify(listener).onResult(true);
9292 
9293         when(mClientModeManager.enableTdls(TEST_BSSID, false)).thenReturn(false);
9294         mWifiServiceImpl.enableTdlsWithRemoteMacAddress(TEST_BSSID, false, listener);
9295         mLooper.dispatchAll();
9296         inOrder.verify(listener).onResult(false);
9297         verify(mLastCallerInfoManager)
9298                 .put(eq(WifiManager.API_SET_TDLS_ENABLED_WITH_MAC_ADDRESS),
9299                 anyInt(), anyInt(), anyInt(), anyString(), eq(false));
9300     }
9301 
9302     @Test
testEnabledTdlsWithIpAddressCallback()9303     public void testEnabledTdlsWithIpAddressCallback() throws RemoteException {
9304         IBooleanListener listener = mock(IBooleanListener.class);
9305         InOrder inOrder = inOrder(listener);
9306 
9307         when(mClientModeManager.enableTdlsWithRemoteIpAddress(TEST_IP, true))
9308                 .thenReturn(true);
9309         mWifiServiceImpl.enableTdlsWithRemoteIpAddress(TEST_IP, true, listener);
9310         mLooper.dispatchAll();
9311         inOrder.verify(listener).onResult(true);
9312 
9313         when(mClientModeManager.enableTdlsWithRemoteIpAddress(TEST_IP, false))
9314                 .thenReturn(false);
9315         mWifiServiceImpl.enableTdlsWithRemoteIpAddress(TEST_IP, false, listener);
9316         mLooper.dispatchAll();
9317         inOrder.verify(listener).onResult(false);
9318         verify(mLastCallerInfoManager)
9319                 .put(eq(WifiManager.API_SET_TDLS_ENABLED),
9320                         anyInt(), anyInt(), anyInt(), anyString(), eq(false));
9321     }
9322 
9323     @Test
testIsTdlsOperationCurrentlyAvailable()9324     public void testIsTdlsOperationCurrentlyAvailable() throws RemoteException {
9325         IBooleanListener listener = mock(IBooleanListener.class);
9326         InOrder inOrder = inOrder(listener);
9327 
9328         when(mClientModeManager.isTdlsOperationCurrentlyAvailable()).thenReturn(true);
9329         mWifiServiceImpl.isTdlsOperationCurrentlyAvailable(listener);
9330         mLooper.dispatchAll();
9331         inOrder.verify(listener).onResult(true);
9332 
9333         when(mClientModeManager.isTdlsOperationCurrentlyAvailable()).thenReturn(false);
9334         mWifiServiceImpl.isTdlsOperationCurrentlyAvailable(listener);
9335         mLooper.dispatchAll();
9336         inOrder.verify(listener).onResult(false);
9337     }
9338 
9339     @Test
testGetMaxSupportedConcurrentTdlsSessions()9340     public void testGetMaxSupportedConcurrentTdlsSessions() throws RemoteException {
9341         assumeTrue(SdkLevel.isAtLeastU());
9342         IIntegerListener listener = mock(IIntegerListener.class);
9343 
9344         when(mClientModeManager.getMaxSupportedConcurrentTdlsSessions()).thenReturn(5);
9345         mWifiServiceImpl.getMaxSupportedConcurrentTdlsSessions(listener);
9346         mLooper.dispatchAll();
9347         verify(listener).onResult(5);
9348     }
9349 
9350     @Test
testGetNumberOfEnabledTdlsSessions()9351     public void testGetNumberOfEnabledTdlsSessions() throws RemoteException {
9352         IIntegerListener listener = mock(IIntegerListener.class);
9353 
9354         when(mClientModeManager.getNumberOfEnabledTdlsSessions()).thenReturn(3);
9355         mWifiServiceImpl.getNumberOfEnabledTdlsSessions(listener);
9356         mLooper.dispatchAll();
9357         verify(listener).onResult(3);
9358     }
9359 
9360     /**
9361      * Verify that a call to setOverrideCountryCode() throws a SecurityException if the caller does
9362      * not have the MANAGE_WIFI_COUNTRY_CODE permission.
9363      */
9364     @Test
testSetOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions()9365     public void testSetOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions() {
9366         assumeTrue(SdkLevel.isAtLeastS());
9367         doThrow(new SecurityException()).when(mContext)
9368                 .enforceCallingOrSelfPermission(eq(MANAGE_WIFI_COUNTRY_CODE),
9369                         eq("WifiService"));
9370         try {
9371             mWifiServiceImpl.setOverrideCountryCode(TEST_COUNTRY_CODE);
9372             fail("expected SecurityException");
9373         } catch (SecurityException expected) { }
9374     }
9375 
9376     /**
9377      * Verify the call to setOverrideCountryCode() goes to WifiCountryCode
9378      */
9379     @Test
testSetOverrideCountryCode()9380     public void testSetOverrideCountryCode() throws Exception {
9381         assumeTrue(SdkLevel.isAtLeastS());
9382         mWifiServiceImpl.setOverrideCountryCode(TEST_COUNTRY_CODE);
9383         mLooper.dispatchAll();
9384         verify(mWifiCountryCode).setOverrideCountryCode(TEST_COUNTRY_CODE);
9385     }
9386 
9387     /**
9388      * Verify that a call to clearOverrideCountryCode() throws a SecurityException if the caller
9389      * does not have the MANAGE_WIFI_COUNTRY_CODE permission.
9390      */
9391     @Test
testClearOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions()9392     public void testClearOverrideCountryCodeThrowsSecurityExceptionOnMissingPermissions() {
9393         assumeTrue(SdkLevel.isAtLeastS());
9394         doThrow(new SecurityException()).when(mContext)
9395                 .enforceCallingOrSelfPermission(eq(MANAGE_WIFI_COUNTRY_CODE),
9396                         eq("WifiService"));
9397         try {
9398             mWifiServiceImpl.clearOverrideCountryCode();
9399             fail("expected SecurityException");
9400         } catch (SecurityException expected) { }
9401     }
9402 
9403     /**
9404      * Verify the call to clearOverrideCountryCode() goes to WifiCountryCode
9405      */
9406     @Test
testClearOverrideCountryCode()9407     public void testClearOverrideCountryCode() throws Exception {
9408         assumeTrue(SdkLevel.isAtLeastS());
9409         mWifiServiceImpl.clearOverrideCountryCode();
9410         mLooper.dispatchAll();
9411         verify(mWifiCountryCode).clearOverrideCountryCode();
9412     }
9413 
9414     /**
9415      * Verify that a call to setDefaultCountryCode() throws a SecurityException if the caller does
9416      * not have the MANAGE_WIFI_COUNTRY_CODE permission.
9417      */
9418     @Test
testSetDefaultCountryCodeThrowsSecurityExceptionOnMissingPermissions()9419     public void testSetDefaultCountryCodeThrowsSecurityExceptionOnMissingPermissions() {
9420         assumeTrue(SdkLevel.isAtLeastS());
9421         doThrow(new SecurityException()).when(mContext)
9422                 .enforceCallingOrSelfPermission(eq(MANAGE_WIFI_COUNTRY_CODE),
9423                         eq("WifiService"));
9424         try {
9425             mWifiServiceImpl.setDefaultCountryCode(TEST_COUNTRY_CODE);
9426             fail("expected SecurityException");
9427         } catch (SecurityException expected) { }
9428     }
9429 
9430     /**
9431      * Verify the call to setDefaultCountryCode() goes to WifiCountryCode
9432      */
9433     @Test
testSetDefaultCountryCode()9434     public void testSetDefaultCountryCode() throws Exception {
9435         assumeTrue(SdkLevel.isAtLeastS());
9436         mWifiServiceImpl.setDefaultCountryCode(TEST_COUNTRY_CODE);
9437         mLooper.dispatchAll();
9438         verify(mWifiCountryCode).setDefaultCountryCode(TEST_COUNTRY_CODE);
9439     }
9440 
9441     /**
9442      * Verify that a call to flushPasspointAnqpCache throws a SecurityException if the
9443      * caller does not have any permission.
9444      */
9445     @Test (expected = SecurityException.class)
testFlushPasspointAnqpCacheThrowsSecurityExceptionOnMissingPermissions()9446     public void testFlushPasspointAnqpCacheThrowsSecurityExceptionOnMissingPermissions() {
9447         when(mContext.checkCallingOrSelfPermission(anyString()))
9448                 .thenReturn(PackageManager.PERMISSION_DENIED);
9449         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), anyString())).thenReturn(false);
9450         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), anyString())).thenReturn(false);
9451 
9452         mWifiServiceImpl.flushPasspointAnqpCache(mContext.getPackageName());
9453     }
9454 
9455     /**
9456      * Verifies that the call to testFlushPasspointAnqpCache with DO permission calls Passpoint
9457      * manager to flush the ANQP cache and clear all pending requests.
9458      */
9459     @Test
testFlushPasspointAnqpCacheWithDoPermissions()9460     public void testFlushPasspointAnqpCacheWithDoPermissions() {
9461         when(mContext.checkCallingOrSelfPermission(anyString()))
9462                 .thenReturn(PackageManager.PERMISSION_DENIED);
9463 
9464         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(true);
9465         when(mWifiPermissionsUtil.isProfileOwner(anyInt(),
9466                 eq(TEST_PACKAGE_NAME))).thenReturn(false);
9467         mWifiServiceImpl.flushPasspointAnqpCache(TEST_PACKAGE_NAME);
9468         mLooper.dispatchAll();
9469         verify(mPasspointManager).clearAnqpRequestsAndFlushCache();
9470     }
9471 
9472     /**
9473      * Verifies that the call to testFlushPasspointAnqpCache with PO permission calls Passpoint
9474      * manager to flush the ANQP cache and clear all pending requests.
9475      */
9476     @Test
testFlushPasspointAnqpCacheWithPoPermissions()9477     public void testFlushPasspointAnqpCacheWithPoPermissions() {
9478         when(mContext.checkCallingOrSelfPermission(anyString()))
9479                 .thenReturn(PackageManager.PERMISSION_DENIED);
9480 
9481         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(false);
9482         when(mWifiPermissionsUtil.isProfileOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(true);
9483         mWifiServiceImpl.flushPasspointAnqpCache(TEST_PACKAGE_NAME);
9484         mLooper.dispatchAll();
9485         verify(mPasspointManager).clearAnqpRequestsAndFlushCache();
9486     }
9487 
9488     /**
9489      * Verifies that the call to testFlushPasspointAnqpCache calls Passpoint manager to flush the
9490      * ANQP cache and clear all pending requests.
9491      */
9492     @Test
testFlushPasspointAnqpCache()9493     public void testFlushPasspointAnqpCache() {
9494         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission.NETWORK_SETTINGS))
9495                 .thenReturn(PackageManager.PERMISSION_GRANTED);
9496         when(mWifiPermissionsUtil.isDeviceOwner(anyInt(), eq(TEST_PACKAGE_NAME))).thenReturn(false);
9497         when(mWifiPermissionsUtil.isProfileOwner(anyInt(),
9498                 eq(TEST_PACKAGE_NAME))).thenReturn(false);
9499         mWifiServiceImpl.flushPasspointAnqpCache(TEST_PACKAGE_NAME);
9500         mLooper.dispatchAll();
9501         verify(mPasspointManager).clearAnqpRequestsAndFlushCache();
9502     }
9503 
9504     /**
9505      * Verify that a call to getUsableChannels() throws a SecurityException if the caller does
9506      * not have the LOCATION_HARDWARE permission.
9507      */
9508     @Test
testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissions()9509     public void testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissions() {
9510         assumeTrue(SdkLevel.isAtLeastS());
9511         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
9512         doThrow(new SecurityException()).when(mWifiPermissionsUtil)
9513                 .checkCallersHardwareLocationPermission(anyInt());
9514         try {
9515             mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY,
9516                     TEST_PACKAGE_NAME, mExtras);
9517             fail("expected SecurityException");
9518         } catch (SecurityException expected) { }
9519     }
9520 
9521     @Test
testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissionsAfterU()9522     public void testGetUsableChannelsThrowsSecurityExceptionOnMissingPermissionsAfterU() {
9523         assumeTrue(SdkLevel.isAtLeastU());
9524 
9525         // verify app targeting prior to Android U can call API with location permission
9526         when(mWifiPermissionsUtil.isTargetSdkLessThan(any(),
9527                 eq(Build.VERSION_CODES.UPSIDE_DOWN_CAKE),
9528                 anyInt())).thenReturn(true);
9529         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
9530         when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt()))
9531                 .thenReturn(true);
9532 
9533         mLooper.startAutoDispatch();
9534         mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY,
9535                 TEST_PACKAGE_NAME, mExtras);
9536 
9537         // Verify app targeting prior to Android U fails to call API without location permission
9538         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(false);
9539         assertThrows(SecurityException.class,
9540                 () -> mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA,
9541                         FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras));
9542 
9543         // Verify app targeting Android U no longer need location.
9544         when(mWifiPermissionsUtil.isTargetSdkLessThan(any(),
9545                 eq(Build.VERSION_CODES.UPSIDE_DOWN_CAKE),
9546                 anyInt())).thenReturn(false);
9547         mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY,
9548                 TEST_PACKAGE_NAME, mExtras);
9549 
9550         // Verify app targeting Android U will fail without nearby permission
9551         doThrow(new SecurityException())
9552                 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
9553                         any(), anyBoolean(), any());
9554         assertThrows(SecurityException.class,
9555                 () -> mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA,
9556                         FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras));
9557         mLooper.stopAutoDispatch();
9558     }
9559 
9560     /**
9561      * Verify the call to isValidBandForGetUsableChannels()
9562      */
9563     @Test
testIsValidBandForGetUsableChannels()9564     public void testIsValidBandForGetUsableChannels() throws Exception {
9565         assumeTrue(SdkLevel.isAtLeastS());
9566         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9567                 WifiScanner.WIFI_BAND_UNSPECIFIED), true);
9568         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9569                 WifiScanner.WIFI_BAND_24_GHZ), true);
9570         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9571                 WifiScanner.WIFI_BAND_5_GHZ), false);
9572         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9573                 WifiScanner.WIFI_BAND_BOTH), false);
9574         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9575                 WifiScanner.WIFI_BAND_5_GHZ_DFS_ONLY), false);
9576         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9577                 WifiScanner.WIFI_BAND_24_GHZ_WITH_5GHZ_DFS), false);
9578         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9579                 WifiScanner.WIFI_BAND_5_GHZ_WITH_DFS), true);
9580         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9581                 WifiScanner.WIFI_BAND_BOTH_WITH_DFS), true);
9582         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9583                 WifiScanner.WIFI_BAND_6_GHZ), true);
9584         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9585                 WifiScanner.WIFI_BAND_24_5_6_GHZ), false);
9586         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9587                 WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_GHZ), true);
9588         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9589                 WifiScanner.WIFI_BAND_60_GHZ), true);
9590         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9591                 WifiScanner.WIFI_BAND_24_5_6_60_GHZ), false);
9592         assertEquals(WifiServiceImpl.isValidBandForGetUsableChannels(
9593                 WifiScanner.WIFI_BAND_24_5_WITH_DFS_6_60_GHZ), true);
9594     }
9595 
9596     /**
9597      * Verify that a call to getUsableChannels() throws an IllegalArgumentException
9598      * if the band specified is invalid for getAllowedChannels() method.
9599      */
9600     @Test
testGetUsableChannelsThrowsIllegalArgumentExceptionOnInValidBand()9601     public void testGetUsableChannelsThrowsIllegalArgumentExceptionOnInValidBand() {
9602         assumeTrue(SdkLevel.isAtLeastS());
9603         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
9604         when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt()))
9605                 .thenReturn(true);
9606         try {
9607             mWifiServiceImpl.getUsableChannels(WIFI_BAND_5_GHZ, OP_MODE_STA, FILTER_REGULATORY,
9608                     TEST_PACKAGE_NAME, mExtras);
9609             fail("expected IllegalArgumentException");
9610         } catch (IllegalArgumentException expected) {
9611         }
9612     }
9613 
9614     /**
9615      * Verify the call to getUsableChannels() goes to WifiNative
9616      */
9617     @Test
testGetUsableChannels()9618     public void testGetUsableChannels() throws Exception {
9619         assumeTrue(SdkLevel.isAtLeastS());
9620         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
9621         when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt()))
9622                 .thenReturn(true);
9623         mLooper.startAutoDispatch();
9624         mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA, FILTER_REGULATORY,
9625                 TEST_PACKAGE_NAME, mExtras);
9626         mLooper.stopAutoDispatch();
9627         verify(mWifiNative).getUsableChannels(anyInt(), anyInt(), anyInt());
9628     }
9629 
9630     /**
9631      * Verify the call to getUsableChannels() goes to cached SoftAp capabilities
9632      */
9633     @Test
testGetUsableChannelsUsesStoredSoftApChannelsWhenDriverIsntUp()9634     public void testGetUsableChannelsUsesStoredSoftApChannelsWhenDriverIsntUp() throws Exception {
9635         mWifiServiceImpl.handleBootCompleted();
9636         mLooper.dispatchAll();
9637         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
9638         when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt()))
9639                 .thenReturn(true);
9640         when(mWifiNative.isHalSupported()).thenReturn(true);
9641         when(mWifiNative.isHalStarted()).thenReturn(false);
9642         setup5GhzSupported();
9643         setup6GhzSupported();
9644         setup60GhzSupported();
9645         when(mWifiCountryCode.getCountryCode()).thenReturn(TEST_COUNTRY_CODE);
9646 
9647         // No values stored
9648         assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_SAP,
9649                 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).isEmpty();
9650 
9651         // Country code doesn't match
9652         when(mWifiSettingsConfigStore.get(WifiSettingsConfigStore.WIFI_SOFT_AP_COUNTRY_CODE))
9653                 .thenReturn(TEST_COUNTRY_CODE);
9654         when(mWifiSettingsConfigStore.get(WifiSettingsConfigStore.WIFI_AVAILABLE_SOFT_AP_FREQS_MHZ))
9655                 .thenReturn("[2452,5180,5955,58320]");
9656         when(mWifiCountryCode.getCountryCode()).thenReturn(TEST_NEW_COUNTRY_CODE);
9657         assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_SAP,
9658                 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).isEmpty();
9659 
9660         // Matching country code
9661         when(mWifiCountryCode.getCountryCode()).thenReturn(TEST_COUNTRY_CODE);
9662         assertThat(mWifiServiceImpl.getUsableChannels(WIFI_BAND_24_5_WITH_DFS_6_60_GHZ, OP_MODE_SAP,
9663                 FILTER_REGULATORY, TEST_PACKAGE_NAME, mExtras)).containsExactly(
9664                 new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP),
9665                 new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP),
9666                 new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP),
9667                 new WifiAvailableChannel(58320, WifiAvailableChannel.OP_MODE_SAP));
9668     }
9669 
9670     /**
9671      * Verify that driver country code updates store the new available Soft AP channels.
9672      */
9673     @Test
testDriverCountryCodeChangedStoresAvailableSoftApChannels()9674     public void testDriverCountryCodeChangedStoresAvailableSoftApChannels() throws Exception {
9675         mWifiServiceImpl.handleBootCompleted();
9676         mLooper.dispatchAll();
9677         when(mWifiPermissionsUtil.isLocationModeEnabled()).thenReturn(true);
9678         when(mWifiPermissionsUtil.checkCallersHardwareLocationPermission(anyInt()))
9679                 .thenReturn(true);
9680         when(mWifiNative.isHalSupported()).thenReturn(true);
9681         when(mWifiNative.isHalStarted()).thenReturn(true);
9682         when(mWifiNative.getUsableChannels(eq(WIFI_BAND_24_GHZ), anyInt(), anyInt()))
9683                 .thenReturn(Arrays.asList(
9684                         new WifiAvailableChannel(2452, WifiAvailableChannel.OP_MODE_SAP)));
9685         when(mWifiNative.getUsableChannels(eq(WIFI_BAND_5_GHZ), anyInt(), anyInt()))
9686                 .thenReturn(Arrays.asList(
9687                         new WifiAvailableChannel(5180, WifiAvailableChannel.OP_MODE_SAP)));
9688         when(mWifiNative.getUsableChannels(eq(WIFI_BAND_6_GHZ), anyInt(), anyInt()))
9689                 .thenReturn(Arrays.asList(
9690                         new WifiAvailableChannel(5955, WifiAvailableChannel.OP_MODE_SAP)));
9691         when(mWifiNative.getUsableChannels(eq(WIFI_BAND_60_GHZ), anyInt(), anyInt()))
9692                 .thenReturn(null);
9693 
9694         mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
9695         mLooper.dispatchAll();
9696 
9697         verify(mWifiSettingsConfigStore).put(
9698                 eq(WifiSettingsConfigStore.WIFI_SOFT_AP_COUNTRY_CODE), eq(TEST_COUNTRY_CODE));
9699         verify(mWifiSettingsConfigStore).put(
9700                 eq(WifiSettingsConfigStore.WIFI_AVAILABLE_SOFT_AP_FREQS_MHZ),
9701                 eq("[2452,5180,5955]"));
9702     }
9703 
setupMultiTypeConfigs( long featureFlags, boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled)9704     private List<WifiConfiguration> setupMultiTypeConfigs(
9705             long featureFlags, boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled) {
9706         when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(featureFlags);
9707         when(mWifiGlobals.isWpa3SaeUpgradeEnabled()).thenReturn(saeAutoUpgradeEnabled);
9708         when(mWifiGlobals.isOweUpgradeEnabled()).thenReturn(oweAutoUpgradeEnabled);
9709 
9710         List<WifiConfiguration> multiTypeConfigs  = new ArrayList<>();
9711         multiTypeConfigs.add(WifiConfigurationTestUtil.createOpenOweNetwork());
9712         multiTypeConfigs.add(WifiConfigurationTestUtil.createPskSaeNetwork());
9713         multiTypeConfigs.add(WifiConfigurationTestUtil.createWpa2Wpa3EnterpriseNetwork());
9714         return multiTypeConfigs;
9715     }
9716 
isSecurityParamsSupported(SecurityParams params, long wifiFeatures)9717     private boolean isSecurityParamsSupported(SecurityParams params, long wifiFeatures) {
9718         switch (params.getSecurityType()) {
9719             case WifiConfiguration.SECURITY_TYPE_SAE:
9720                 return 0 != (wifiFeatures & WifiManager.WIFI_FEATURE_WPA3_SAE);
9721             case WifiConfiguration.SECURITY_TYPE_OWE:
9722                 return 0 != (wifiFeatures & WifiManager.WIFI_FEATURE_OWE);
9723         }
9724         return true;
9725     }
9726 
generateExpectedConfigs( List<WifiConfiguration> testConfigs, boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled)9727     private List<WifiConfiguration> generateExpectedConfigs(
9728             List<WifiConfiguration> testConfigs,
9729             boolean saeAutoUpgradeEnabled, boolean oweAutoUpgradeEnabled) {
9730         if (!SdkLevel.isAtLeastS()) {
9731             return testConfigs;
9732         }
9733         WifiConfiguration tmpConfig;
9734         List<WifiConfiguration> expectedConfigs = new ArrayList<>();
9735         tmpConfig = new WifiConfiguration(testConfigs.get(0));
9736         tmpConfig.setSecurityParams(
9737                 SecurityParams.createSecurityParamsBySecurityType(
9738                         WifiConfiguration.SECURITY_TYPE_OPEN));
9739         expectedConfigs.add(tmpConfig);
9740         if (oweAutoUpgradeEnabled) {
9741             tmpConfig = new WifiConfiguration(testConfigs.get(0));
9742             tmpConfig.setSecurityParams(
9743                     SecurityParams.createSecurityParamsBySecurityType(
9744                             WifiConfiguration.SECURITY_TYPE_OWE));
9745             expectedConfigs.add(tmpConfig);
9746         }
9747         tmpConfig = new WifiConfiguration(testConfigs.get(1));
9748         tmpConfig.setSecurityParams(
9749                 SecurityParams.createSecurityParamsBySecurityType(
9750                         WifiConfiguration.SECURITY_TYPE_PSK));
9751         expectedConfigs.add(tmpConfig);
9752         if (saeAutoUpgradeEnabled) {
9753             tmpConfig = new WifiConfiguration(testConfigs.get(1));
9754             tmpConfig.setSecurityParams(
9755                     SecurityParams.createSecurityParamsBySecurityType(
9756                             WifiConfiguration.SECURITY_TYPE_SAE));
9757             expectedConfigs.add(tmpConfig);
9758         }
9759         tmpConfig = new WifiConfiguration(testConfigs.get(2));
9760         tmpConfig.setSecurityParams(
9761                 SecurityParams.createSecurityParamsBySecurityType(
9762                         WifiConfiguration.SECURITY_TYPE_EAP));
9763         expectedConfigs.add(tmpConfig);
9764         tmpConfig = new WifiConfiguration(testConfigs.get(2));
9765         tmpConfig.setSecurityParams(
9766                 SecurityParams.createSecurityParamsBySecurityType(
9767                         WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE));
9768         expectedConfigs.add(tmpConfig);
9769         return expectedConfigs;
9770     }
9771 
9772     /**
9773      * verify multi-type configs are converted to legacy configs in getConfiguredNetworks
9774      * and getPrivilegedConfiguredNetworks when auto-upgrade is enabled.
9775      */
9776     @Test
testGetConfiguredNetworksForMultiTypeConfigs()9777     public void testGetConfiguredNetworksForMultiTypeConfigs() {
9778         long featureFlags = WifiManager.WIFI_FEATURE_WPA3_SAE | WifiManager.WIFI_FEATURE_OWE;
9779         List<WifiConfiguration> testConfigs = setupMultiTypeConfigs(
9780                 featureFlags, true, true);
9781         when(mWifiConfigManager.getSavedNetworks(anyInt()))
9782                 .thenReturn(testConfigs);
9783         when(mWifiConfigManager.getConfiguredNetworksWithPasswords())
9784                 .thenReturn(testConfigs);
9785         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
9786                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
9787 
9788         mLooper.startAutoDispatch();
9789         ParceledListSlice<WifiConfiguration> configs =
9790                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false);
9791         ParceledListSlice<WifiConfiguration> privilegedConfigs =
9792                 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID,
9793                         mExtras);
9794         mLooper.stopAutoDispatchAndIgnoreExceptions();
9795 
9796         List<WifiConfiguration> expectedConfigs = generateExpectedConfigs(
9797                 testConfigs, true, true);
9798         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
9799                 expectedConfigs, configs.getList());
9800         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
9801                 expectedConfigs, privilegedConfigs.getList());
9802     }
9803 
9804     /**
9805      * verify multi-type configs are converted to legacy configs in getConfiguredNetworks
9806      * and getPrivilegedConfiguredNetworks when auto-upgrade is not enabled.
9807      */
9808     @Test
testGetConfiguredNetworksForMultiTypeConfigsWithoutAutoUpgradeEnabled()9809     public void testGetConfiguredNetworksForMultiTypeConfigsWithoutAutoUpgradeEnabled() {
9810         long featureFlags = WifiManager.WIFI_FEATURE_WPA3_SAE | WifiManager.WIFI_FEATURE_OWE;
9811         List<WifiConfiguration> testConfigs = setupMultiTypeConfigs(
9812                 featureFlags, false, false);
9813         when(mWifiConfigManager.getSavedNetworks(anyInt()))
9814                 .thenReturn(testConfigs);
9815         when(mWifiConfigManager.getConfiguredNetworksWithPasswords())
9816                 .thenReturn(testConfigs);
9817         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
9818                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
9819 
9820         mLooper.startAutoDispatch();
9821         ParceledListSlice<WifiConfiguration> configs =
9822                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false);
9823         ParceledListSlice<WifiConfiguration> privilegedConfigs =
9824                 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID,
9825                         mExtras);
9826         mLooper.stopAutoDispatchAndIgnoreExceptions();
9827 
9828         List<WifiConfiguration> expectedConfigs = generateExpectedConfigs(
9829                 testConfigs, false, false);
9830         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
9831                 expectedConfigs, configs.getList());
9832         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
9833                 expectedConfigs, privilegedConfigs.getList());
9834     }
9835 
9836     /**
9837      * verify multi-type configs are converted to legacy configs in getConfiguredNetworks
9838      * and getPrivilegedConfiguredNetworks when security types are not supported.
9839      */
9840     @Test
testGetConfiguredNetworksForMultiTypeConfigsWithoutHwSupport()9841     public void testGetConfiguredNetworksForMultiTypeConfigsWithoutHwSupport() {
9842         long featureFlags = 0L;
9843         List<WifiConfiguration> testConfigs = setupMultiTypeConfigs(
9844                 featureFlags, true, true);
9845         when(mWifiConfigManager.getSavedNetworks(anyInt()))
9846                 .thenReturn(testConfigs);
9847         when(mWifiConfigManager.getConfiguredNetworksWithPasswords())
9848                 .thenReturn(testConfigs);
9849         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
9850                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
9851 
9852         mLooper.startAutoDispatch();
9853         ParceledListSlice<WifiConfiguration> configs =
9854                 mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID, false);
9855         ParceledListSlice<WifiConfiguration> privilegedConfigs =
9856                 mWifiServiceImpl.getPrivilegedConfiguredNetworks(TEST_PACKAGE, TEST_FEATURE_ID,
9857                         mExtras);
9858         mLooper.stopAutoDispatchAndIgnoreExceptions();
9859 
9860         List<WifiConfiguration> expectedConfigs = generateExpectedConfigs(
9861                 testConfigs, true, true);
9862         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
9863                 expectedConfigs, configs.getList());
9864         WifiConfigurationTestUtil.assertConfigurationsEqualForBackup(
9865                 expectedConfigs, privilegedConfigs.getList());
9866     }
9867 
trySetTargetSdkToT()9868     private void trySetTargetSdkToT() {
9869         if (SdkLevel.isAtLeastT()) {
9870             when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
9871                     eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false);
9872         }
9873     }
9874 
9875     @Test (expected = SecurityException.class)
testGetPrivilegedConnectedNetworkNoPermission()9876     public void testGetPrivilegedConnectedNetworkNoPermission() {
9877         trySetTargetSdkToT();
9878         if (SdkLevel.isAtLeastT()) {
9879             doThrow(new SecurityException())
9880                     .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
9881                             any(), anyBoolean(), any());
9882         } else {
9883             doThrow(new SecurityException()).when(mWifiPermissionsUtil)
9884                     .enforceCanAccessScanResults(any(), any(), anyInt(), any());
9885         }
9886 
9887         mWifiServiceImpl.getPrivilegedConnectedNetwork(TEST_PACKAGE_NAME, TEST_FEATURE_ID, mExtras);
9888         mLooper.dispatchAll();
9889     }
9890 
9891     @Test
testGetPrivilegedConnectedNetworkNotConnected()9892     public void testGetPrivilegedConnectedNetworkNotConnected() {
9893         trySetTargetSdkToT();
9894         when(mActiveModeWarden.getConnectionInfo()).thenReturn(new WifiInfo());
9895 
9896         mLooper.startAutoDispatch();
9897         assertNull(mWifiServiceImpl.getPrivilegedConnectedNetwork(
9898                 TEST_PACKAGE_NAME, TEST_FEATURE_ID, mExtras));
9899         mLooper.stopAutoDispatchAndIgnoreExceptions();
9900 
9901         if (SdkLevel.isAtLeastT()) {
9902             verify(mWifiPermissionsUtil).enforceNearbyDevicesPermission(any(), eq(true), any());
9903         } else {
9904             verify(mWifiPermissionsUtil).enforceCanAccessScanResults(any(), any(), anyInt(), any());
9905         }
9906     }
9907 
9908     @Test
testGetPrivilegedConnectedNetworkSuccess()9909     public void testGetPrivilegedConnectedNetworkSuccess() {
9910         // mock testConfig as the currently connected network
9911         trySetTargetSdkToT();
9912         WifiConfiguration testConfig = WifiConfigurationTestUtil.createPskSaeNetwork();
9913         testConfig.networkId = TEST_NETWORK_ID;
9914         testConfig.setRandomizedMacAddress(TEST_FACTORY_MAC_ADDR);
9915         WifiInfo wifiInfo = new WifiInfo();
9916         wifiInfo.setNetworkId(testConfig.networkId);
9917         when(mActiveModeWarden.getConnectionInfo()).thenReturn(wifiInfo);
9918         when(mWifiConfigManager.getConfiguredNetworkWithPassword(testConfig.networkId)).thenReturn(
9919                 testConfig);
9920 
9921         mLooper.startAutoDispatch();
9922         WifiConfiguration result = mWifiServiceImpl.getPrivilegedConnectedNetwork(
9923                 TEST_PACKAGE_NAME, TEST_FEATURE_ID, mExtras);
9924         mLooper.stopAutoDispatchAndIgnoreExceptions();
9925 
9926         if (SdkLevel.isAtLeastT()) {
9927             verify(mWifiPermissionsUtil).enforceNearbyDevicesPermission(any(), eq(true), any());
9928         } else {
9929             verify(mWifiPermissionsUtil).enforceCanAccessScanResults(any(), any(), anyInt(), any());
9930         }
9931         verify(mWifiConfigManager).getConfiguredNetworkWithPassword(testConfig.networkId);
9932         // verify the credentials match
9933         assertEquals(testConfig.networkId, result.networkId);
9934         assertEquals(testConfig.SSID, result.SSID);
9935         assertEquals(testConfig.preSharedKey, result.preSharedKey);
9936         // verify the randomized MAC address is filtered out
9937         assertEquals(WifiInfo.DEFAULT_MAC_ADDRESS, result.getRandomizedMacAddress().toString());
9938     }
9939 
9940     /**
9941      * Verify that a call to isWifiPasspointEnabled throws a SecurityException if the
9942      * caller does not have the ACCESS_WIFI_STATE permission.
9943      */
9944     @Test (expected = SecurityException.class)
testIsWifiPasspointEnabledWithoutPermissions()9945     public void testIsWifiPasspointEnabledWithoutPermissions() {
9946         doThrow(new SecurityException()).when(mContext)
9947                 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE),
9948                         eq("WifiService"));
9949 
9950         mWifiServiceImpl.isWifiPasspointEnabled();
9951     }
9952 
9953     /**
9954      * Verify that the call to setWifiPasspointEnabled is not redirected to
9955      * specific API when the caller doesn't have
9956      * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD.
9957      */
9958     @Test(expected = SecurityException.class)
testSetWifiPasspointEnabledWithoutPermissions()9959     public void testSetWifiPasspointEnabledWithoutPermissions() {
9960         mLooper.startAutoDispatch();
9961         mWifiServiceImpl.setWifiPasspointEnabled(false);
9962         mLooper.stopAutoDispatchAndIgnoreExceptions();
9963     }
9964 
9965     /**
9966      * Verify that the call to setWifiPasspointEnabled is redirected to
9967      * specific API when the caller have
9968      * NETWORK_SETTINGS permissions and NETWORK_SETUP_WIZARD.
9969      */
9970     @Test
testSetWifiPasspointEnabledWithPermissions()9971     public void testSetWifiPasspointEnabledWithPermissions() {
9972         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
9973                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
9974         mLooper.startAutoDispatch();
9975         mWifiServiceImpl.setWifiPasspointEnabled(false);
9976         mLooper.dispatchAll();
9977         mLooper.stopAutoDispatchAndIgnoreExceptions();
9978         verify(mPasspointManager).setWifiPasspointEnabled(false);
9979     }
9980 
9981     @Test(expected = SecurityException.class)
testSetScreenOnScanSchedule_NoPermission()9982     public void testSetScreenOnScanSchedule_NoPermission() {
9983         assumeTrue(SdkLevel.isAtLeastT());
9984         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
9985                 .thenReturn(false);
9986         mWifiServiceImpl.setScreenOnScanSchedule(null, null);
9987     }
9988 
9989     @Test(expected = IllegalArgumentException.class)
testSetScreenOnScanSchedule_BadInput1()9990     public void testSetScreenOnScanSchedule_BadInput1() {
9991         assumeTrue(SdkLevel.isAtLeastT());
9992         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
9993                 .thenReturn(true);
9994         // test that both arrays need to be null or non-null. Never one null one non-null.
9995         mWifiServiceImpl.setScreenOnScanSchedule(null, new int[] {1});
9996     }
9997 
9998     @Test(expected = IllegalArgumentException.class)
testSetScreenOnScanSchedule_BadInput2()9999     public void testSetScreenOnScanSchedule_BadInput2() {
10000         assumeTrue(SdkLevel.isAtLeastT());
10001         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
10002                 .thenReturn(true);
10003         // test that the input should not be empty arrays.
10004         mWifiServiceImpl.setScreenOnScanSchedule(new int[0], new int[0]);
10005     }
10006 
10007     @Test
testSetScreenOnScanSchedule_Success()10008     public void testSetScreenOnScanSchedule_Success() {
10009         assumeTrue(SdkLevel.isAtLeastT());
10010         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
10011                 .thenReturn(true);
10012         int[] expectedSchedule = new int[] {20, 40, 80};
10013         int[] expectedType = new int[] {2, 2, 1};
10014         mWifiServiceImpl.setScreenOnScanSchedule(expectedSchedule, expectedType);
10015         mLooper.dispatchAll();
10016         verify(mWifiConnectivityManager).setExternalScreenOnScanSchedule(
10017                 expectedSchedule, expectedType);
10018         verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_SCAN_SCHEDULE), anyInt(),
10019                 anyInt(), anyInt(), any(), eq(true));
10020 
10021         mWifiServiceImpl.setScreenOnScanSchedule(null, null);
10022         mLooper.dispatchAll();
10023         verify(mWifiConnectivityManager).setExternalScreenOnScanSchedule(null, null);
10024         verify(mLastCallerInfoManager).put(eq(WifiManager.API_SET_SCAN_SCHEDULE), anyInt(),
10025                 anyInt(), anyInt(), any(), eq(false));
10026     }
10027 
10028     @Test
testSetOneShotScreenOnConnectivityScanDelayMillis()10029     public void testSetOneShotScreenOnConnectivityScanDelayMillis() {
10030         assumeTrue(SdkLevel.isAtLeastT());
10031         int delayMs = 1234;
10032 
10033         // verify permission checks
10034         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
10035                 .thenReturn(false);
10036         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt()))
10037                 .thenReturn(false);
10038         assertThrows(SecurityException.class,
10039                 () -> mWifiServiceImpl.setOneShotScreenOnConnectivityScanDelayMillis(delayMs));
10040 
10041         // verify correct input
10042         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
10043                 .thenReturn(true);
10044         assertThrows(IllegalArgumentException.class,
10045                 () -> mWifiServiceImpl.setOneShotScreenOnConnectivityScanDelayMillis(-1));
10046 
10047         // verify correct call
10048         mWifiServiceImpl.setOneShotScreenOnConnectivityScanDelayMillis(delayMs);
10049         mLooper.dispatchAll();
10050         verify(mWifiConnectivityManager).setOneShotScreenOnConnectivityScanDelayMillis(delayMs);
10051     }
10052 
10053     @Test(expected = SecurityException.class)
testSetExternalPnoScanRequest_NoPermission()10054     public void testSetExternalPnoScanRequest_NoPermission() {
10055         assumeTrue(SdkLevel.isAtLeastT());
10056         IPnoScanResultsCallback callback = mock(IPnoScanResultsCallback.class);
10057         List<WifiSsid> ssids = new ArrayList<>();
10058         ssids.add(WifiSsid.fromString("\"TEST_SSID_1\""));
10059         int[] frequencies = new int[] {TEST_AP_FREQUENCY};
10060 
10061         mWifiServiceImpl.setExternalPnoScanRequest(mAppBinder, callback, ssids, frequencies,
10062                 TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10063     }
10064 
10065     @Test
testSetExternalPnoScanRequest_Success()10066     public void testSetExternalPnoScanRequest_Success() throws Exception {
10067         assumeTrue(SdkLevel.isAtLeastT());
10068         when(mActiveModeWarden.getSupportedFeatureSet())
10069                 .thenReturn(WifiManager.WIFI_FEATURE_PNO);
10070         when(mWifiPermissionsUtil.checkRequestCompanionProfileAutomotiveProjectionPermission(
10071                 anyInt())).thenReturn(true);
10072         when(mWifiPermissionsUtil.checkCallersLocationPermissionInManifest(
10073                 anyInt(), anyBoolean())).thenReturn(true);
10074         IPnoScanResultsCallback callback = mock(IPnoScanResultsCallback.class);
10075         List<WifiSsid> ssids = new ArrayList<>();
10076         ssids.add(WifiSsid.fromString("\"TEST_SSID_1\""));
10077         int[] frequencies = new int[] {TEST_AP_FREQUENCY};
10078 
10079         mWifiServiceImpl.setExternalPnoScanRequest(mAppBinder, callback, ssids, frequencies,
10080                 TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10081         mLooper.dispatchAll();
10082         verify(mWifiConnectivityManager).setExternalPnoScanRequest(anyInt(), any(), any(),
10083                 eq(callback), eq(ssids), eq(frequencies));
10084     }
10085 
10086     @Test
testSetExternalPnoScanRequest_PnoNotSupported()10087     public void testSetExternalPnoScanRequest_PnoNotSupported() throws Exception {
10088         assumeTrue(SdkLevel.isAtLeastT());
10089         when(mActiveModeWarden.getSupportedFeatureSet()).thenReturn(0L);
10090         when(mWifiPermissionsUtil.checkRequestCompanionProfileAutomotiveProjectionPermission(
10091                 anyInt())).thenReturn(true);
10092         when(mWifiPermissionsUtil.checkCallersLocationPermissionInManifest(
10093                 anyInt(), anyBoolean())).thenReturn(true);
10094         IPnoScanResultsCallback callback = mock(IPnoScanResultsCallback.class);
10095         List<WifiSsid> ssids = new ArrayList<>();
10096         ssids.add(WifiSsid.fromString("\"TEST_SSID_1\""));
10097         int[] frequencies = new int[] {TEST_AP_FREQUENCY};
10098 
10099         mWifiServiceImpl.setExternalPnoScanRequest(mAppBinder, callback, ssids, frequencies,
10100                 TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10101         mLooper.dispatchAll();
10102         verify(callback).onRegisterFailed(WifiManager.PnoScanResultsCallback
10103                 .REGISTER_PNO_CALLBACK_PNO_NOT_SUPPORTED);
10104     }
10105 
10106     @Test
testClearExternalPnoScanRequest()10107     public void testClearExternalPnoScanRequest() {
10108         assumeTrue(SdkLevel.isAtLeastT());
10109 
10110         mWifiServiceImpl.clearExternalPnoScanRequest();
10111         mLooper.dispatchAll();
10112         verify(mWifiConnectivityManager).clearExternalPnoScanRequest(anyInt());
10113     }
10114 
10115     @Test
testGetLastCallerInfoForApi_Exceptions()10116     public void testGetLastCallerInfoForApi_Exceptions() {
10117         // good inputs should result in no exceptions.
10118         ILastCallerListener listener = mock(ILastCallerListener.class);
10119         // null listener ==> IllegalArgumentException
10120         assertThrows(IllegalArgumentException.class,
10121                 () -> mWifiServiceImpl.getLastCallerInfoForApi(
10122                         WifiManager.API_WIFI_ENABLED, null));
10123 
10124         // invalid ApiType ==> IllegalArgumentException
10125         assertThrows(IllegalArgumentException.class,
10126                 () -> mWifiServiceImpl.getLastCallerInfoForApi(WifiManager.API_MAX + 1, listener));
10127 
10128         // No permission ==> SecurityException
10129         assertThrows(SecurityException.class,
10130                 () -> mWifiServiceImpl.getLastCallerInfoForApi(
10131                         WifiManager.API_WIFI_ENABLED, listener));
10132     }
10133 
10134     @Test
testGetLastCallerInfoForApi_GoodCase()10135     public void testGetLastCallerInfoForApi_GoodCase() throws RemoteException {
10136         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
10137         ILastCallerListener listener = mock(ILastCallerListener.class);
10138         LastCallerInfoManager.LastCallerInfo expected =
10139                 new LastCallerInfoManager.LastCallerInfo(0, 1, 2, TEST_PACKAGE_NAME, true);
10140         when(mLastCallerInfoManager.get(WifiManager.API_WIFI_ENABLED)).thenReturn(expected);
10141 
10142         InOrder inOrder = inOrder(listener);
10143         mWifiServiceImpl.getLastCallerInfoForApi(WifiManager.API_WIFI_ENABLED, listener);
10144         mLooper.dispatchAll();
10145         inOrder.verify(listener).onResult(TEST_PACKAGE_NAME, true);
10146 
10147         // Verify null is returned as packageName if there's no information about this ApiType.
10148         mWifiServiceImpl.getLastCallerInfoForApi(WifiManager.API_SOFT_AP, listener);
10149         mLooper.dispatchAll();
10150         inOrder.verify(listener).onResult(null, false);
10151     }
10152 
10153     /**
10154      * Verify that a call to registerDriverCountryCodeChangedListener throws a SecurityException
10155      * if the caller doesnot have ACCESS_COARSE_LOCATION permission.
10156      */
10157     @Test(expected = SecurityException.class)
registerDriverCountryCodeChangedListenerThrowsSecurityExceptionWithoutPermission()10158     public void registerDriverCountryCodeChangedListenerThrowsSecurityExceptionWithoutPermission() {
10159         assumeTrue(SdkLevel.isAtLeastT());
10160         doThrow(new SecurityException())
10161                 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(), eq(true));
10162         mWifiServiceImpl.registerDriverCountryCodeChangedListener(
10163                 mIOnWifiDriverCountryCodeChangedListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10164     }
10165 
10166     /**
10167      * Verify that a call registerDriverCountryCodeChangedListener throws an
10168      * IllegalArgumentException if the parameters are not provided.
10169      */
10170     @Test
registerDriverCountryCodeChangedListenerThrowsIllegalArgumentException()10171     public void registerDriverCountryCodeChangedListenerThrowsIllegalArgumentException() {
10172         assumeTrue(SdkLevel.isAtLeastT());
10173         try {
10174             mWifiServiceImpl.registerDriverCountryCodeChangedListener(
10175                     null, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10176             fail("expected IllegalArgumentException");
10177         } catch (IllegalArgumentException expected) {
10178         }
10179     }
10180 
10181     /**
10182      * Verifies that we handle driver country code changed listener registration failure if we
10183      * encounter an exception while linking to death.
10184      */
10185     @Test
registerDriverCountryCodeChangedListenerFailureOnLinkToDeath()10186     public void registerDriverCountryCodeChangedListenerFailureOnLinkToDeath() throws Exception {
10187         assumeTrue(SdkLevel.isAtLeastT());
10188         doThrow(new RemoteException())
10189                 .when(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
10190         mWifiServiceImpl.registerDriverCountryCodeChangedListener(
10191                 mIOnWifiDriverCountryCodeChangedListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10192         mLooper.dispatchAll();
10193         verify(mIOnWifiDriverCountryCodeChangedListener, never())
10194                 .onDriverCountryCodeChanged(anyString());
10195     }
10196 
10197     /**
10198      * Verify that a call to registerDriverCountryCodeChangedListener succeeded.
10199      */
verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener( IOnWifiDriverCountryCodeChangedListener listener)10200     private void verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener(
10201             IOnWifiDriverCountryCodeChangedListener listener)
10202             throws Exception {
10203         doNothing()
10204                 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(),
10205                                                                       eq(true));
10206         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(eq(TEST_PACKAGE_NAME),
10207                 eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true);
10208         when(mWifiCountryCode.getCurrentDriverCountryCode()).thenReturn(TEST_COUNTRY_CODE);
10209         mWifiServiceImpl.registerDriverCountryCodeChangedListener(
10210                 listener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10211         mLooper.dispatchAll();
10212         verify(listener)
10213                 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
10214     }
10215 
10216     /**
10217      * Verify that a call to registerDriverCountryCodeChangedListener succeeded but we don't nofiy
10218      * listener because permission gets denied in OpNote.
10219      */
10220     @Test
verifyRegisterDriverCountryCodeChangedListenerSucceededButNoNotifyListener()10221     public void verifyRegisterDriverCountryCodeChangedListenerSucceededButNoNotifyListener()
10222             throws Exception {
10223         assumeTrue(SdkLevel.isAtLeastT());
10224         doNothing()
10225                 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(),
10226                                                                       eq(true));
10227         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(eq(TEST_PACKAGE_NAME),
10228                 eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(false);
10229         when(mWifiCountryCode.getCurrentDriverCountryCode()).thenReturn(TEST_COUNTRY_CODE);
10230         mWifiServiceImpl.registerDriverCountryCodeChangedListener(
10231                   mIOnWifiDriverCountryCodeChangedListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
10232         mLooper.dispatchAll();
10233         verify(mIOnWifiDriverCountryCodeChangedListener, never())
10234                 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
10235     }
10236 
10237     /**
10238      * Verify that DriverCountryCodeChanged will be dropped if register permission was removed.
10239      */
10240     @Test
testDriverCountryCodeChangedDropWhenRegisterPermissionRemoved()10241     public void testDriverCountryCodeChangedDropWhenRegisterPermissionRemoved() throws Exception {
10242         assumeTrue(SdkLevel.isAtLeastT());
10243         doNothing()
10244                 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(),
10245                                                                       eq(true));
10246         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
10247                 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true);
10248         verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener(
10249                 mIOnWifiDriverCountryCodeChangedListener);
10250         mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE);
10251         mLooper.dispatchAll();
10252         verify(mIOnWifiDriverCountryCodeChangedListener)
10253                 .onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE);
10254         // remove permission
10255         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
10256                 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(false);
10257         reset(mIOnWifiDriverCountryCodeChangedListener);
10258         mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
10259         mLooper.dispatchAll();
10260         verify(mIOnWifiDriverCountryCodeChangedListener, never())
10261                 .onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
10262     }
10263 
10264     /**
10265      * Verify that unregisterDriverCountryCodeChangedListener removes listener from registered
10266      * listener list
10267      */
10268     @Test
unregisterDriverCountryCodeChangedListenerRemovesListener()10269     public void unregisterDriverCountryCodeChangedListenerRemovesListener() throws Exception {
10270         assumeTrue(SdkLevel.isAtLeastT());
10271         doNothing()
10272                 .when(mWifiPermissionsUtil).enforceLocationPermissionInManifest(anyInt(),
10273                                                                       eq(true));
10274         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
10275                 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true);
10276         verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener(
10277                 mIOnWifiDriverCountryCodeChangedListener);
10278         mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE);
10279         mLooper.dispatchAll();
10280         verify(mIOnWifiDriverCountryCodeChangedListener)
10281                 .onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE);
10282         mWifiServiceImpl.unregisterDriverCountryCodeChangedListener(
10283                 mIOnWifiDriverCountryCodeChangedListener);
10284         mLooper.dispatchAll();
10285         reset(mIOnWifiDriverCountryCodeChangedListener);
10286         mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
10287         mLooper.dispatchAll();
10288         verify(mIOnWifiDriverCountryCodeChangedListener, never())
10289                 .onDriverCountryCodeChanged(anyString());
10290     }
10291 
10292 
10293     /**
10294      * Verify that onFailed is called when enabling Lohs with non-supported configuration.
10295      */
10296     @Test
testFailureCallbacksTriggeredWhenSoftApFailsBecauseNonSupportedConfiguration()10297     public void testFailureCallbacksTriggeredWhenSoftApFailsBecauseNonSupportedConfiguration()
10298             throws Exception {
10299         when(mResources.getBoolean(R.bool.config_wifiSoftap6ghzSupported)).thenReturn(false);
10300         setupForCustomLohs();
10301         SoftApConfiguration lohsConfig = createValidSoftApConfiguration();
10302         SoftApConfiguration customizedConfig = new SoftApConfiguration.Builder(lohsConfig)
10303                 .setBand(SoftApConfiguration.BAND_6GHZ)
10304                 .setPassphrase("thisIsABadPassword", SoftApConfiguration.SECURITY_TYPE_WPA3_SAE)
10305                 .build();
10306         when(mWifiApConfigStore.generateLocalOnlyHotspotConfig(
10307                 any(), any(), any())).thenReturn(customizedConfig);
10308         // Expect the result is registered but it should get failure because non-supported
10309         // configuration
10310         int result = mWifiServiceImpl.startLocalOnlyHotspot(mLohsCallback, TEST_PACKAGE_NAME,
10311                 TEST_FEATURE_ID, customizedConfig, mExtras);
10312         assertEquals(LocalOnlyHotspotCallback.REQUEST_REGISTERED, result);
10313         mLooper.dispatchAll();
10314         verify(mLohsCallback).onHotspotFailed(ERROR_GENERIC);
10315     }
10316     /**
10317      * Registers a soft AP callback, then verifies that the current soft AP state and num clients
10318      * are sent to caller immediately after callback is registered.
10319      */
registerLohsSoftApCallbackAndVerify(ISoftApCallback callback, Bundle bundle)10320     private void registerLohsSoftApCallbackAndVerify(ISoftApCallback callback, Bundle bundle)
10321             throws Exception {
10322         mWifiServiceImpl.registerLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, bundle);
10323         mLooper.dispatchAll();
10324         verify(mClientSoftApCallback).onStateChanged(WIFI_AP_STATE_DISABLED, 0);
10325         verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged(
10326                 new HashMap<String, SoftApInfo>(),
10327                 new HashMap<String, List<WifiClient>>(), false, true);
10328         verify(mClientSoftApCallback).onCapabilityChanged(
10329                 ApConfigUtil.updateCapabilityFromResource(mContext));
10330         // Don't need to invoke callback when register.
10331         verify(mClientSoftApCallback, never()).onBlockedClientConnecting(any(), anyInt());
10332     }
10333 
10334     /**
10335      * Verify that unregisterLocalOnlyHotspotSoftApCallback removes callback from registered
10336      * callbacks list.
10337      */
10338     @Test
unregisterLohsSoftApCallbackRemovesCallback()10339     public void unregisterLohsSoftApCallbackRemovesCallback() throws Exception {
10340         assumeTrue(SdkLevel.isAtLeastT());
10341         registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras);
10342 
10343         mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras);
10344         mLooper.dispatchAll();
10345 
10346         reset(mClientSoftApCallback);
10347         mLohsApCallback.onConnectedClientsOrInfoChanged(
10348                 mTestSoftApInfos, mTestSoftApClients, false);
10349         mLooper.dispatchAll();
10350         verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged(
10351                 any(), any(), anyBoolean(), anyBoolean());
10352     }
10353 
10354     /**
10355      * Verify that unregisterLocalOnlyHotspotSoftApCallback is no-op if callback not registered.
10356      */
10357     @Test
unregisterLohsSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching()10358     public void unregisterLohsSoftApCallbackDoesNotRemoveCallbackIfCallbackNotMatching()
10359             throws Exception {
10360         assumeTrue(SdkLevel.isAtLeastT());
10361         registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras);
10362 
10363         mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mAnotherSoftApCallback, mExtras);
10364         mLooper.dispatchAll();
10365         mLohsApCallback.onConnectedClientsOrInfoChanged(
10366                 mTestSoftApInfos, mTestSoftApClients, false);
10367         mLooper.dispatchAll();
10368         verify(mClientSoftApCallback).onConnectedClientsOrInfoChanged(
10369                 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(false));
10370     }
10371 
10372     /**
10373      * Registers two lohs callbacks, remove one then verify the right callback is being called
10374      * on events.
10375      */
10376     @Test
correctLohsCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne()10377     public void correctLohsCallbackIsCalledAfterAddingTwoCallbacksAndRemovingOne()
10378             throws Exception {
10379         assumeTrue(SdkLevel.isAtLeastT());
10380         WifiClient testWifiClient = new WifiClient(MacAddress.fromString("22:33:44:55:66:77"),
10381                 WIFI_IFACE_NAME2);
10382         registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras);
10383         mLooper.dispatchAll();
10384 
10385         reset(mClientSoftApCallback);
10386         when(mClientSoftApCallback.asBinder()).thenReturn(mAppBinder);
10387         // Change state from default before registering the second callback
10388         mLohsApCallback.onStateChanged(WIFI_AP_STATE_ENABLED, 0);
10389         mLohsApCallback.onConnectedClientsOrInfoChanged(
10390                 mTestSoftApInfos, mTestSoftApClients, false);
10391         mLohsApCallback.onBlockedClientConnecting(testWifiClient, 0);
10392 
10393 
10394         // Register another callback and verify the new state is returned in the immediate callback
10395         mWifiServiceImpl.registerLocalOnlyHotspotSoftApCallback(mAnotherSoftApCallback, mExtras);
10396         mLooper.dispatchAll();
10397         verify(mAnotherSoftApCallback).onStateChanged(WIFI_AP_STATE_ENABLED, 0);
10398         verify(mAnotherSoftApCallback).onConnectedClientsOrInfoChanged(
10399                 eq(mTestSoftApInfos), eq(mTestSoftApClients), eq(false), eq(true));
10400         // Verify only first callback will receive onBlockedClientConnecting since it call after
10401         // first callback register but before another callback register.
10402         verify(mClientSoftApCallback).onBlockedClientConnecting(testWifiClient, 0);
10403         verify(mAnotherSoftApCallback, never()).onBlockedClientConnecting(testWifiClient, 0);
10404 
10405         // unregister the fisrt callback
10406         mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras);
10407         mLooper.dispatchAll();
10408 
10409         // Update soft AP state and verify the remaining callback receives the event
10410         mLohsApCallback.onStateChanged(WIFI_AP_STATE_FAILED,
10411                 SAP_START_FAILURE_NO_CHANNEL);
10412         mLooper.dispatchAll();
10413         verify(mClientSoftApCallback, never()).onStateChanged(WIFI_AP_STATE_FAILED,
10414                 SAP_START_FAILURE_NO_CHANNEL);
10415         verify(mAnotherSoftApCallback).onStateChanged(WIFI_AP_STATE_FAILED,
10416                 SAP_START_FAILURE_NO_CHANNEL);
10417     }
10418 
10419     /**
10420      * Verify that wifi service registers for lohs callers BinderDeath event
10421      */
10422     @Test
registersForBinderDeathOnRegisterLohsSoftApCallback()10423     public void registersForBinderDeathOnRegisterLohsSoftApCallback() throws Exception {
10424         assumeTrue(SdkLevel.isAtLeastT());
10425         registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras);
10426         verify(mAppBinder).linkToDeath(any(IBinder.DeathRecipient.class), anyInt());
10427     }
10428 
10429     /**
10430      * Verify that we un-register the lohs soft AP callback on receiving BinderDied event.
10431      */
10432     @Test
unregistersLohsSoftApCallbackOnBinderDied()10433     public void unregistersLohsSoftApCallbackOnBinderDied() throws Exception {
10434         assumeTrue(SdkLevel.isAtLeastT());
10435         ArgumentCaptor<IBinder.DeathRecipient> drCaptor =
10436                 ArgumentCaptor.forClass(IBinder.DeathRecipient.class);
10437         registerLohsSoftApCallbackAndVerify(mClientSoftApCallback, mExtras);
10438         verify(mAppBinder).linkToDeath(drCaptor.capture(), anyInt());
10439 
10440         drCaptor.getValue().binderDied();
10441         mLooper.dispatchAll();
10442         reset(mClientSoftApCallback);
10443         // Verify callback is removed from the list as well
10444         Map<String, List<WifiClient>> mTestSoftApClients = mock(Map.class);
10445         Map<String, SoftApInfo> mTestSoftApInfos = mock(Map.class);
10446         mLohsApCallback.onConnectedClientsOrInfoChanged(
10447                 mTestSoftApInfos, mTestSoftApClients, false);
10448         mLooper.dispatchAll();
10449         verify(mClientSoftApCallback, never()).onConnectedClientsOrInfoChanged(
10450                 any(), any(), anyBoolean(), anyBoolean());
10451     }
10452 
10453     /**
10454      * Verify that a call to registerLocalOnlyHotspotSoftApCallback throws a SecurityException
10455      * if the caller target Android T or later and does not have nearby devices permission.
10456      */
10457     @Test(expected = SecurityException.class)
testRegisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT()10458     public void testRegisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT() {
10459         assumeTrue(SdkLevel.isAtLeastT());
10460         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
10461                 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false);
10462         doThrow(new SecurityException())
10463                 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
10464                         any(), anyBoolean(), any());
10465         mWifiServiceImpl.registerLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras);
10466     }
10467 
10468     /**
10469      * Verify that a call to unregisterLocalOnlyHotspotSoftApCallback throws a SecurityException
10470      * if the caller targets Android T or later and does not have nearby devices permission.
10471      */
10472     @Test(expected = SecurityException.class)
testUnregisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT()10473     public void testUnregisterLocalOnlyHotspotSoftApCallbackThrowsExceptionWithoutPermissionOnT() {
10474         assumeTrue(SdkLevel.isAtLeastT());
10475         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
10476                 eq(Build.VERSION_CODES.TIRAMISU), anyInt())).thenReturn(false);
10477         doThrow(new SecurityException())
10478                 .when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
10479                         any(), anyBoolean(), any());
10480         mWifiServiceImpl.unregisterLocalOnlyHotspotSoftApCallback(mClientSoftApCallback, mExtras);
10481     }
10482 
10483     /**
10484      * Verify getStaConcurrencyForMultiInternetMode
10485      */
10486     @Test
testGetStaConcurrencyForMultiInternetMode()10487     public void testGetStaConcurrencyForMultiInternetMode() throws Exception {
10488         assumeTrue(SdkLevel.isAtLeastT());
10489         when(mMultiInternetManager.getStaConcurrencyForMultiInternetMode()).thenReturn(
10490                 WifiManager.WIFI_MULTI_INTERNET_MODE_DBS_AP);
10491         mLooper.startAutoDispatch();
10492         final int mode = mWifiServiceImpl.getStaConcurrencyForMultiInternetMode();
10493         verify(mMultiInternetManager).getStaConcurrencyForMultiInternetMode();
10494         assertEquals(WifiManager.WIFI_MULTI_INTERNET_MODE_DBS_AP, mode);
10495     }
10496 
10497     /**
10498      * Verify that a call to setStaConcurrencyForMultiInternetMode throws a SecurityException
10499      * if the caller target Android T or later and does not have network settings permission.
10500      */
10501     @Test(expected = SecurityException.class)
testSetStaConcurrencyForMultiInternetModeThrowsExceptionWithoutPermissionOnT()10502     public void testSetStaConcurrencyForMultiInternetModeThrowsExceptionWithoutPermissionOnT() {
10503         assumeTrue(SdkLevel.isAtLeastT());
10504         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
10505         when(mWifiPermissionsUtil.checkNetworkSetupWizardPermission(anyInt())).thenReturn(false);
10506         doThrow(new SecurityException()).when(mContext)
10507                 .enforceCallingOrSelfPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10508                                                 eq("WifiService"));
10509         mLooper.startAutoDispatch();
10510         mWifiServiceImpl.setStaConcurrencyForMultiInternetMode(
10511                 WifiManager.WIFI_MULTI_INTERNET_MODE_DBS_AP);
10512     }
10513 
10514     /**
10515      * Verify setStaConcurrencyForMultiInternetMode
10516      */
10517     @Test
testSetStaConcurrencyForMultiInternetMode()10518     public void testSetStaConcurrencyForMultiInternetMode() throws Exception {
10519         assumeTrue(SdkLevel.isAtLeastT());
10520         when(mMultiInternetManager.setStaConcurrencyForMultiInternetMode(anyInt()))
10521                 .thenReturn(true);
10522         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10523                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10524         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETUP_WIZARD),
10525                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10526         mLooper.startAutoDispatch();
10527         assertTrue(mWifiServiceImpl.setStaConcurrencyForMultiInternetMode(
10528                 WifiManager.WIFI_MULTI_INTERNET_MODE_MULTI_AP));
10529         verify(mMultiInternetManager).setStaConcurrencyForMultiInternetMode(
10530                 WifiManager.WIFI_MULTI_INTERNET_MODE_MULTI_AP);
10531     }
10532 
10533     /**
10534      * Verify attribution is passed in correctly by WifiManager#addOrUpdateNetwork.
10535      */
10536     @Test
testAddOrUpdateNetworkAttribution_InvalidAttributions()10537     public void testAddOrUpdateNetworkAttribution_InvalidAttributions() {
10538         assumeTrue(SdkLevel.isAtLeastS());
10539         AttributionSource attributionSource = mock(AttributionSource.class);
10540         when(attributionSource.checkCallingUid()).thenReturn(true);
10541         when(attributionSource.isTrusted(any(Context.class))).thenReturn(true);
10542         mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource);
10543         mWifiServiceImpl = spy(mWifiServiceImpl);
10544         lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID);
10545         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
10546         assertThrows(SecurityException.class, () -> {
10547             mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, null);
10548         });
10549 
10550         assertThrows(SecurityException.class, () -> {
10551             mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, new Bundle());
10552         });
10553 
10554         assertThrows(SecurityException.class, () -> {
10555             Bundle nullEntry = new Bundle();
10556             nullEntry.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, null);
10557             mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, nullEntry);
10558         });
10559 
10560         assertThrows(SecurityException.class, () -> {
10561             Bundle incorrectEntry = new Bundle();
10562             incorrectEntry.putInt(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, 10);
10563             mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, incorrectEntry);
10564         });
10565 
10566         when(attributionSource.checkCallingUid()).thenReturn(false);
10567         assertThrows(SecurityException.class, () -> {
10568             mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution);
10569         });
10570         when(attributionSource.checkCallingUid()).thenReturn(true); // restore
10571 
10572         // single first attributions should not fail - even if (theoretically, doesn't happen in
10573         // practice) are not trusted. I.e. this call checks that this method isn't called.
10574         AttributionSource freshAs = mock(AttributionSource.class);
10575         Bundle freshAttribution = new Bundle();
10576         freshAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, freshAs);
10577         when(freshAs.checkCallingUid()).thenReturn(true);
10578         when(freshAs.isTrusted(any(Context.class))).thenReturn(false);
10579         mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, freshAttribution);
10580         verify(freshAs, never()).isTrusted(any());
10581 
10582         AttributionSource originalCaller = mock(AttributionSource.class);
10583         when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID);
10584         when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER);
10585         when(originalCaller.isTrusted(any(Context.class))).thenReturn(false);
10586         when(attributionSource.getNext()).thenReturn(originalCaller);
10587         assertThrows(SecurityException.class, () -> {
10588             mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution);
10589         });
10590     }
10591 
10592     /**
10593      * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's no chain.
10594      */
10595     @Test
testAddOrUpdateNetworkAttribution_CorrectParsingNoChainSystemServer()10596     public void testAddOrUpdateNetworkAttribution_CorrectParsingNoChainSystemServer() {
10597         assumeTrue(SdkLevel.isAtLeastS());
10598         AttributionSource attributionSource = mock(AttributionSource.class);
10599         when(attributionSource.checkCallingUid()).thenReturn(true);
10600         when(attributionSource.isTrusted(any(Context.class))).thenReturn(true);
10601         mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource);
10602         mWifiServiceImpl = spy(mWifiServiceImpl);
10603         lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID);
10604         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10605                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10606         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false)))
10607                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
10608         when(attributionSource.getUid()).thenReturn(Process.SYSTEM_UID);
10609         when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME);
10610         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
10611         config.networkId = 1;
10612         mWifiThreadRunner.prepareForAutoDispatch();
10613         mLooper.startAutoDispatch();
10614         mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution);
10615         mLooper.stopAutoDispatch();
10616         verify(mWifiConfigManager).addOrUpdateNetwork(config, Process.SYSTEM_UID,
10617                 TEST_PACKAGE_NAME, false);
10618         verify(mLastCallerInfoManager).put(eq(WifiManager.API_UPDATE_NETWORK), anyInt(),
10619                 anyInt(), anyInt(), anyString(), eq(true));
10620     }
10621 
10622     /**
10623      * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's no chain.
10624      */
10625     @Test
testAddOrUpdateNetworkAttribution_CorrectParsingNoChainNonSystemServer()10626     public void testAddOrUpdateNetworkAttribution_CorrectParsingNoChainNonSystemServer() {
10627         assumeTrue(SdkLevel.isAtLeastS());
10628         mWifiServiceImpl = spy(mWifiServiceImpl);
10629         lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID);
10630         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10631                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10632         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false)))
10633                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
10634         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
10635 
10636         mWifiThreadRunner.prepareForAutoDispatch();
10637         mLooper.startAutoDispatch();
10638         mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, null);
10639         mLooper.stopAutoDispatch();
10640         verify(mWifiConfigManager).addOrUpdateNetwork(config, TEST_UID, TEST_PACKAGE_NAME, false);
10641     }
10642 
10643     /**
10644      * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's a chain.
10645      */
10646     @Test
testAddOrUpdateNetworkAttribution_CorrectParsingWithChain()10647     public void testAddOrUpdateNetworkAttribution_CorrectParsingWithChain() {
10648         assumeTrue(SdkLevel.isAtLeastS());
10649         AttributionSource attributionSource = mock(AttributionSource.class);
10650         when(attributionSource.checkCallingUid()).thenReturn(true);
10651         when(attributionSource.isTrusted(any(Context.class))).thenReturn(true);
10652         mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource);
10653         mWifiServiceImpl = spy(mWifiServiceImpl);
10654         lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID);
10655         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10656                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10657         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false)))
10658                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
10659 
10660         when(attributionSource.getUid()).thenReturn(TEST_UID);
10661         when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME);
10662         AttributionSource originalCaller = mock(AttributionSource.class);
10663         when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID);
10664         when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER);
10665         when(originalCaller.isTrusted(any(Context.class))).thenReturn(true);
10666         when(attributionSource.getNext()).thenReturn(originalCaller);
10667 
10668         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
10669 
10670         mWifiThreadRunner.prepareForAutoDispatch();
10671         mLooper.startAutoDispatch();
10672         mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution);
10673         mLooper.stopAutoDispatch();
10674         verify(mWifiConfigManager).addOrUpdateNetwork(config, OTHER_TEST_UID,
10675                 TEST_PACKAGE_NAME_OTHER, false);
10676     }
10677 
10678     /**
10679      * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's a chain,
10680      * When calling from {@link WifiManager#updateNetwork(WifiConfiguration)}, the creator will be
10681      * overridden by original caller.
10682      */
10683     @Test
testAddOrUpdateNetworkAttribution_CorrectParsingWithChain_WithUpdateNetwork()10684     public void testAddOrUpdateNetworkAttribution_CorrectParsingWithChain_WithUpdateNetwork() {
10685         assumeTrue(SdkLevel.isAtLeastS());
10686         AttributionSource attributionSource = mock(AttributionSource.class);
10687         when(attributionSource.checkCallingUid()).thenReturn(true);
10688         when(attributionSource.isTrusted(any(Context.class))).thenReturn(true);
10689         mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource);
10690         mWifiServiceImpl = spy(mWifiServiceImpl);
10691         lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(Process.SYSTEM_UID);
10692         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10693                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10694         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(true)))
10695                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
10696 
10697         when(attributionSource.getUid()).thenReturn(TEST_UID);
10698         when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME);
10699         AttributionSource originalCaller = mock(AttributionSource.class);
10700         when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID);
10701         when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER);
10702         when(originalCaller.isTrusted(any(Context.class))).thenReturn(true);
10703         when(attributionSource.getNext()).thenReturn(originalCaller);
10704 
10705         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
10706         config.networkId = TEST_NETWORK_ID;
10707 
10708         mWifiThreadRunner.prepareForAutoDispatch();
10709         mLooper.startAutoDispatch();
10710         mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution);
10711         mLooper.stopAutoDispatch();
10712         verify(mWifiConfigManager).addOrUpdateNetwork(config, OTHER_TEST_UID,
10713                 TEST_PACKAGE_NAME_OTHER, true);
10714     }
10715 
10716     /**
10717      * Verify attribution passed to WifiManager#addOrUpdateNetwork is parsed when there's a chain.
10718      * However, if the call is not made from the system server then the attribution is ignored and
10719      * the attribution is simply to the calling app as before.
10720      */
10721     @Test
testAddOrUpdateNetworkAttribution_CorrectParsingWithChainButNotFromSystemServer()10722     public void testAddOrUpdateNetworkAttribution_CorrectParsingWithChainButNotFromSystemServer() {
10723         assumeTrue(SdkLevel.isAtLeastS());
10724         AttributionSource attributionSource = mock(AttributionSource.class);
10725         when(attributionSource.checkCallingUid()).thenReturn(true);
10726         when(attributionSource.isTrusted(any(Context.class))).thenReturn(true);
10727         mAttribution.putParcelable(EXTRA_PARAM_KEY_ATTRIBUTION_SOURCE, attributionSource);
10728         mWifiServiceImpl = spy(mWifiServiceImpl);
10729         lenient().when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID);
10730         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
10731                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10732         when(mWifiConfigManager.addOrUpdateNetwork(any(), anyInt(), anyString(), eq(false)))
10733                 .thenReturn(new NetworkUpdateResult(TEST_NETWORK_ID));
10734 
10735         when(attributionSource.getUid()).thenReturn(TEST_UID);
10736         when(attributionSource.getPackageName()).thenReturn(TEST_PACKAGE_NAME);
10737         AttributionSource originalCaller = mock(AttributionSource.class);
10738         when(originalCaller.getUid()).thenReturn(OTHER_TEST_UID);
10739         when(originalCaller.getPackageName()).thenReturn(TEST_PACKAGE_NAME_OTHER);
10740         when(originalCaller.isTrusted(any(Context.class))).thenReturn(true);
10741         when(attributionSource.getNext()).thenReturn(originalCaller);
10742 
10743         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
10744 
10745         mWifiThreadRunner.prepareForAutoDispatch();
10746         mLooper.startAutoDispatch();
10747         mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME, mAttribution);
10748         mLooper.stopAutoDispatch();
10749         verify(mWifiConfigManager).addOrUpdateNetwork(config, TEST_UID,
10750                 TEST_PACKAGE_NAME, false);
10751     }
10752 
10753     /**
10754      * Test that notifyWifiSsidPolicyChanged disconnects the current network
10755      * due to SSID allowlist restriction
10756      */
10757     @Test
testNotifyWifiSsidPolicyChangedWithAllowlistRestriction()10758     public void testNotifyWifiSsidPolicyChangedWithAllowlistRestriction()
10759             throws Exception {
10760         assumeTrue(SdkLevel.isAtLeastT());
10761 
10762         WifiInfo wifiInfo = new WifiInfo();
10763         wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID));
10764         wifiInfo.setBSSID(TEST_BSSID);
10765         wifiInfo.setNetworkId(TEST_NETWORK_ID);
10766         wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PSK);
10767 
10768         when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS),
10769                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10770         when(mActiveModeWarden.getClientModeManagers()).thenReturn(
10771                 Collections.singletonList(mClientModeManager));
10772         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
10773 
10774         mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST,
10775                 Arrays.asList(WifiSsid.fromUtf8Text("SSID")));
10776         mLooper.dispatchAll();
10777 
10778         verify(mClientModeManager).disconnect();
10779     }
10780 
10781     /**
10782      * Test that notifyWifiSsidPolicyChanged disconnects the current network
10783      * due to SSID denylist restriction
10784      */
10785     @Test
testNotifyWifiSsidPolicyChangedWithDenylistRestriction()10786     public void testNotifyWifiSsidPolicyChangedWithDenylistRestriction()
10787             throws Exception {
10788         assumeTrue(SdkLevel.isAtLeastT());
10789 
10790         WifiInfo wifiInfo = new WifiInfo();
10791         wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID));
10792         wifiInfo.setBSSID(TEST_BSSID);
10793         wifiInfo.setNetworkId(TEST_NETWORK_ID);
10794         wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PSK);
10795 
10796         when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS),
10797                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10798         when(mActiveModeWarden.getClientModeManagers()).thenReturn(
10799                 Collections.singletonList(mClientModeManager));
10800         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
10801 
10802         mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST,
10803                 Arrays.asList(WifiSsid.fromUtf8Text(TEST_SSID)));
10804         mLooper.dispatchAll();
10805 
10806         verify(mClientModeManager).disconnect();
10807     }
10808 
10809     /**
10810      * Test that notifyWifiSsidPolicyChanged does not disconnect the current network
10811      * due to SSID restriction for Passpoint networks
10812      */
10813     @Test
testNotifyWifiSsidPolicyChangedWithSsidRestrictionForPasspoint()10814     public void testNotifyWifiSsidPolicyChangedWithSsidRestrictionForPasspoint()
10815             throws Exception {
10816         assumeTrue(SdkLevel.isAtLeastT());
10817 
10818         WifiInfo wifiInfo = setupForGetConnectionInfo();
10819         wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PASSPOINT_R1_R2);
10820 
10821         when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS),
10822                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10823         when(mActiveModeWarden.getClientModeManagers()).thenReturn(
10824                 Collections.singletonList(mClientModeManager));
10825         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
10826 
10827         mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST,
10828                 Arrays.asList(WifiSsid.fromUtf8Text("SSID")));
10829         mLooper.dispatchAll();
10830 
10831         verify(mClientModeManager, never()).disconnect();
10832     }
10833 
10834     /**
10835      * Test that notifyWifiSsidPolicyChanged does not disconnect the current network
10836      * due to SSID restriction for Osu networks
10837      */
10838     @Test
testNotifyWifiSsidPolicyChangedWithSsidRestrictionForOsu()10839     public void testNotifyWifiSsidPolicyChangedWithSsidRestrictionForOsu()
10840             throws Exception {
10841         assumeTrue(SdkLevel.isAtLeastT());
10842 
10843         WifiInfo wifiInfo = new WifiInfo();
10844         wifiInfo.setSSID(WifiSsid.fromUtf8Text(TEST_SSID));
10845         wifiInfo.setBSSID(TEST_BSSID);
10846         wifiInfo.setNetworkId(TEST_NETWORK_ID);
10847         wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PASSPOINT_R3);
10848         wifiInfo.setOsuAp(true);
10849 
10850         when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS),
10851                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10852         when(mActiveModeWarden.getClientModeManagers()).thenReturn(
10853                 Collections.singletonList(mClientModeManager));
10854         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
10855 
10856         mWifiServiceImpl.notifyWifiSsidPolicyChanged(WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_DENYLIST,
10857                 Arrays.asList(WifiSsid.fromUtf8Text(TEST_SSID)));
10858         mLooper.dispatchAll();
10859 
10860         verify(mClientModeManager, never()).disconnect();
10861     }
10862 
10863     /**
10864      * Test that notifyMinimumRequiredWifiSecurityLevelChanged disconnects the current network
10865      * due to minimum security level restriction
10866      */
10867     @Test
testNotifyMinimumRequiredWifiSecurityLevelChangedWithSecurityLevelRestriction()10868     public void testNotifyMinimumRequiredWifiSecurityLevelChangedWithSecurityLevelRestriction()
10869             throws Exception {
10870         assumeTrue(SdkLevel.isAtLeastT());
10871 
10872         WifiInfo wifiInfo = setupForGetConnectionInfo();
10873         wifiInfo.setCurrentSecurityType(WifiConfiguration.SECURITY_TYPE_PSK);
10874 
10875         when(mContext.checkPermission(eq(android.Manifest.permission.MANAGE_DEVICE_ADMINS),
10876                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
10877         when(mActiveModeWarden.getClientModeManagers()).thenReturn(
10878                 Collections.singletonList(mClientModeManager));
10879         when(mClientModeManager.getConnectionInfo()).thenReturn(wifiInfo);
10880 
10881         mWifiServiceImpl.notifyMinimumRequiredWifiSecurityLevelChanged(
10882                 DevicePolicyManager.WIFI_SECURITY_ENTERPRISE_EAP);
10883         mLooper.dispatchAll();
10884 
10885         verify(mClientModeManager).disconnect();
10886     }
10887 
10888     @Test
testIsItPossibleToCreateInterfaceInvalidConditions()10889     public void testIsItPossibleToCreateInterfaceInvalidConditions() {
10890         assumeTrue(SdkLevel.isAtLeastT());
10891 
10892         when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(anyInt())).thenReturn(true);
10893         IInterfaceCreationInfoCallback.Stub mockCallback = mock(
10894                 IInterfaceCreationInfoCallback.Stub.class);
10895 
10896         assertThrows(IllegalArgumentException.class,
10897                 () -> mWifiServiceImpl.reportCreateInterfaceImpact(null,
10898                         WifiManager.WIFI_INTERFACE_TYPE_AP, true, mockCallback));
10899         assertThrows(IllegalArgumentException.class,
10900                 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME,
10901                         WifiManager.WIFI_INTERFACE_TYPE_AP, true, null));
10902         assertThrows(IllegalArgumentException.class,
10903                 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME,
10904                         /* clearly invalid value */ 100, true, mockCallback));
10905 
10906         mWifiServiceImpl = spy(mWifiServiceImpl);
10907         when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID);
10908         doThrow(new SecurityException()).when(mWifiPermissionsUtil).checkPackage(TEST_UID,
10909                 TEST_PACKAGE_NAME);
10910         assertThrows(SecurityException.class,
10911                 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME,
10912                         WifiManager.WIFI_INTERFACE_TYPE_AP, false, mockCallback));
10913 
10914         when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(anyInt())).thenReturn(false);
10915         assertThrows(SecurityException.class,
10916                 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME,
10917                         WifiManager.WIFI_INTERFACE_TYPE_AP, false, mockCallback));
10918 
10919         when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(anyInt())).thenReturn(true);
10920         doThrow(new SecurityException()).when(mContext)
10921                 .enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE),
10922                         eq("WifiService"));
10923         assertThrows(SecurityException.class,
10924                 () -> mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME,
10925                         WifiManager.WIFI_INTERFACE_TYPE_AP, false, mockCallback));
10926     }
10927 
10928     @Test
testIsItPossibleToCreateInterface()10929     public void testIsItPossibleToCreateInterface() throws Exception {
10930         assumeTrue(SdkLevel.isAtLeastT());
10931 
10932         IInterfaceCreationInfoCallback.Stub mockCallback = mock(
10933                 IInterfaceCreationInfoCallback.Stub.class);
10934         final int interfaceToCreate = WifiManager.WIFI_INTERFACE_TYPE_AWARE;
10935         final int interfaceToCreateInternal = HalDeviceManager.HDM_CREATE_IFACE_NAN;
10936         mWifiServiceImpl = spy(mWifiServiceImpl);
10937         when(mWifiServiceImpl.getMockableCallingUid()).thenReturn(TEST_UID);
10938         when(mWifiPermissionsUtil.checkManageWifiInterfacesPermission(TEST_UID)).thenReturn(true);
10939         final WorkSource ws = new WorkSource(TEST_UID, TEST_PACKAGE_NAME);
10940         final WorkSource wsOther = new WorkSource(OTHER_TEST_UID, TEST_PACKAGE_NAME_OTHER);
10941         final String[] packagesOther = {TEST_PACKAGE_NAME_OTHER};
10942 
10943         ArgumentCaptor<Boolean> boolCaptor = ArgumentCaptor.forClass(Boolean.class);
10944         ArgumentCaptor<int[]> intArrayCaptor = ArgumentCaptor.forClass(int[].class);
10945         ArgumentCaptor<String[]> stringArrayCaptor = ArgumentCaptor.forClass(String[].class);
10946 
10947         // 3 results: failure, success with no side effects, success with side effects
10948         when(mHalDeviceManager.reportImpactToCreateIface(interfaceToCreateInternal, true, ws))
10949                 .thenReturn(null)
10950                 .thenReturn(Collections.emptyList())
10951                 .thenReturn(List.of(Pair.create(HalDeviceManager.HDM_CREATE_IFACE_P2P, wsOther)))
10952                 .thenReturn(List.of(Pair.create(HalDeviceManager.HDM_CREATE_IFACE_NAN,
10953                         new WorkSource(WIFI_UID))));
10954         mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true,
10955                 mockCallback);
10956         mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true,
10957                 mockCallback);
10958         mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true,
10959                 mockCallback);
10960         mWifiServiceImpl.reportCreateInterfaceImpact(TEST_PACKAGE_NAME, interfaceToCreate, true,
10961                 mockCallback);
10962         mLooper.dispatchAll();
10963         verify(mHalDeviceManager, times(4)).reportImpactToCreateIface(
10964                 interfaceToCreateInternal, true, ws);
10965         verify(mockCallback, times(4)).onResults(boolCaptor.capture(), intArrayCaptor.capture(),
10966                 stringArrayCaptor.capture());
10967         verify(mPackageManager).makeUidVisible(TEST_UID, OTHER_TEST_UID);
10968 
10969         // result 0: failure
10970         assertFalse(boolCaptor.getAllValues().get(0));
10971         assertNull(intArrayCaptor.getAllValues().get(0));
10972         assertNull(stringArrayCaptor.getAllValues().get(0));
10973 
10974         // result 1: success with no side effects
10975         assertTrue(boolCaptor.getAllValues().get(1));
10976         assertEquals(0, intArrayCaptor.getAllValues().get(1).length);
10977         assertEquals(0, stringArrayCaptor.getAllValues().get(1).length);
10978 
10979         // result 2: success with side effects
10980         assertTrue(boolCaptor.getAllValues().get(2));
10981         assertEquals(1, intArrayCaptor.getAllValues().get(2).length);
10982         assertEquals(WifiManager.WIFI_INTERFACE_TYPE_DIRECT,
10983                 intArrayCaptor.getAllValues().get(2)[0]);
10984         assertArrayEquals(packagesOther, stringArrayCaptor.getAllValues().get(2));
10985 
10986         // result 2: success with side effects of empty packages
10987         assertTrue(boolCaptor.getAllValues().get(3));
10988         assertEquals(1, intArrayCaptor.getAllValues().get(3).length);
10989         assertEquals(WifiManager.WIFI_INTERFACE_TYPE_AWARE,
10990                 intArrayCaptor.getAllValues().get(3)[0]);
10991         assertEquals(1, stringArrayCaptor.getAllValues().get(3).length);
10992         assertNull(stringArrayCaptor.getAllValues().get(3)[0]);
10993     }
10994 
10995     @Test
testTetheredSoftApTrackerWhenCountryCodeChanged()10996     public void testTetheredSoftApTrackerWhenCountryCodeChanged() throws Exception {
10997         mWifiServiceImpl.handleBootCompleted();
10998         mLooper.dispatchAll();
10999 
11000         registerSoftApCallbackAndVerify(mClientSoftApCallback);
11001         reset(mClientSoftApCallback);
11002         when(mWifiPermissionsUtil.checkCallersCoarseLocationPermission(
11003                 eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID), anyInt(), any())).thenReturn(true);
11004         if (SdkLevel.isAtLeastT()) {
11005             verifyRegisterDriverCountryCodeChangedListenerSucceededAndTriggerListener(
11006                     mIOnWifiDriverCountryCodeChangedListener);
11007             reset(mIOnWifiDriverCountryCodeChangedListener);
11008         }
11009         ArgumentCaptor<SoftApCapability> capabilityArgumentCaptor = ArgumentCaptor.forClass(
11010                 SoftApCapability.class);
11011         // Country code update with HAL started
11012         when(mWifiNative.isHalStarted()).thenReturn(true);
11013         // Channel 9 - 2452Mhz
11014         WifiAvailableChannel channels2g = new WifiAvailableChannel(2452,
11015                 WifiAvailableChannel.OP_MODE_SAP);
11016         when(mWifiNative.isHalSupported()).thenReturn(true);
11017         when(mWifiNative.isHalStarted()).thenReturn(true);
11018         when(mWifiNative.getUsableChannels(eq(WifiScanner.WIFI_BAND_24_GHZ), anyInt(), anyInt()))
11019                 .thenReturn(new ArrayList<>(Arrays.asList(channels2g)));
11020         mWifiServiceImpl.mCountryCodeTracker.onCountryCodeChangePending(TEST_COUNTRY_CODE);
11021         mLooper.dispatchAll();
11022         mWifiServiceImpl.mCountryCodeTracker.onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
11023         mLooper.dispatchAll();
11024         if (SdkLevel.isAtLeastT()) {
11025             verify(mIOnWifiDriverCountryCodeChangedListener)
11026                     .onDriverCountryCodeChanged(TEST_COUNTRY_CODE);
11027         }
11028         verify(mClientSoftApCallback).onCapabilityChanged(capabilityArgumentCaptor.capture());
11029         assertEquals(1, capabilityArgumentCaptor.getValue()
11030                 .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ).length);
11031         assertEquals(9, capabilityArgumentCaptor.getValue()
11032                 .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ)[0]);
11033         reset(mClientSoftApCallback);
11034         // Country code update with HAL not started
11035         when(mWifiNative.isHalStarted()).thenReturn(false);
11036         mWifiServiceImpl.mCountryCodeTracker.onCountryCodeChangePending(TEST_NEW_COUNTRY_CODE);
11037         mLooper.dispatchAll();
11038         if (SdkLevel.isAtLeastT()) {
11039             verify(mIOnWifiDriverCountryCodeChangedListener, never())
11040                     .onDriverCountryCodeChanged(TEST_NEW_COUNTRY_CODE);
11041         }
11042         verify(mClientSoftApCallback)
11043                 .onCapabilityChanged(capabilityArgumentCaptor.capture());
11044         // The supported channels in soft AP capability got invalidated.
11045         assertEquals(0, capabilityArgumentCaptor.getValue()
11046                 .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ).length);
11047     }
11048 
11049     /**
11050      * Verify that change network connection state is not allowed for App target below Q SDK from
11051      * guest user
11052      */
11053     @Test
testNotAllowedToChangeWifiOpsTargetBelowQSdkFromGuestUser()11054     public void testNotAllowedToChangeWifiOpsTargetBelowQSdkFromGuestUser() throws Exception {
11055         doReturn(AppOpsManager.MODE_ALLOWED).when(mAppOpsManager)
11056                 .noteOp(AppOpsManager.OPSTR_CHANGE_WIFI_STATE, Process.myUid(), TEST_PACKAGE_NAME);
11057         when(mWifiPermissionsUtil.isTargetSdkLessThan(anyString(),
11058                 eq(Build.VERSION_CODES.Q), anyInt())).thenReturn(true);
11059         when(mWifiPermissionsUtil.isGuestUser()).thenReturn(true);
11060 
11061         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
11062         verify(mWifiMetrics, never()).incrementNumWifiToggles(anyBoolean(), anyBoolean());
11063         verify(mWifiMetrics, never()).reportWifiStateChanged(anyBoolean(), anyBoolean(),
11064                 anyBoolean());
11065 
11066         assertFalse(mWifiServiceImpl.disconnect(TEST_PACKAGE_NAME));
11067         assertFalse(mWifiServiceImpl.reconnect(TEST_PACKAGE_NAME));
11068         assertFalse(mWifiServiceImpl.reassociate(TEST_PACKAGE_NAME));
11069 
11070         assertTrue(mWifiServiceImpl.getConfiguredNetworks(TEST_PACKAGE_NAME, TEST_FEATURE_ID,
11071                 false).getList().isEmpty());
11072         mLooper.dispatchAll();
11073         verify(mWifiConfigManager, never()).getConfiguredNetworks();
11074 
11075         assertFalse(mWifiServiceImpl.removeNetwork(0, TEST_PACKAGE_NAME));
11076         mLooper.dispatchAll();
11077         verify(mWifiConfigManager, never()).removeNetwork(anyInt(), anyInt(), anyString());
11078 
11079         assertFalse(mWifiServiceImpl.enableNetwork(0, false, TEST_PACKAGE_NAME));
11080         mLooper.dispatchAll();
11081         verify(mWifiConfigManager, never()).enableNetwork(anyInt(), anyBoolean(), anyInt(),
11082                 anyString());
11083         verify(mWifiMetrics, never()).incrementNumEnableNetworkCalls();
11084 
11085         assertFalse(mWifiServiceImpl.disableNetwork(0, TEST_PACKAGE_NAME));
11086         mLooper.dispatchAll();
11087         verify(mWifiConfigManager, never()).disableNetwork(anyInt(), anyInt(), anyString());
11088 
11089         PasspointConfiguration passpointConfig = new PasspointConfiguration();
11090         HomeSp homeSp = new HomeSp();
11091         homeSp.setFqdn("test.com");
11092         passpointConfig.setHomeSp(homeSp);
11093         assertFalse(mWifiServiceImpl.addOrUpdatePasspointConfiguration(passpointConfig,
11094                 TEST_PACKAGE_NAME));
11095         mLooper.dispatchAll();
11096         verify(mPasspointManager, never()).addOrUpdateProvider(any(), anyInt(), anyString(),
11097                 anyBoolean(), anyBoolean(), eq(false));
11098 
11099         WifiConfiguration config = WifiConfigurationTestUtil.createOpenNetwork(TEST_SSID);
11100         assertEquals(-1, mWifiServiceImpl.addOrUpdateNetwork(config, TEST_PACKAGE_NAME,
11101                 mAttribution));
11102     }
11103 
11104     /**
11105      * Tests that {@link WifiServiceImpl#getCurrentNetwork} throws
11106      * {@link SecurityException} if the caller doesn't have the necessary permissions.
11107      */
11108     @Test(expected = SecurityException.class)
testGetCurrentNetworkNoPermission()11109     public void testGetCurrentNetworkNoPermission() throws Exception {
11110         doThrow(SecurityException.class)
11111                 .when(mContext).enforceCallingOrSelfPermission(eq(ACCESS_WIFI_STATE), any());
11112         mWifiServiceImpl.getCurrentNetwork();
11113     }
11114 
11115     /**
11116      * Verifies that WifiServiceImpl#getCurrentNetwork() returns the current Wifi network.
11117      */
11118     @Test
testGetCurrentNetworkWithNetworkSettingsPermission()11119     public void testGetCurrentNetworkWithNetworkSettingsPermission() throws Exception {
11120         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
11121                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
11122         Network mockNetwork = mock(Network.class);
11123         when(mActiveModeWarden.getCurrentNetwork()).thenReturn(mockNetwork);
11124         assertEquals(mockNetwork, mWifiServiceImpl.getCurrentNetwork());
11125     }
11126 
11127     @Test
testQueryLastConfiguredTetheredApPassphraseSinceBootExceptions()11128     public void testQueryLastConfiguredTetheredApPassphraseSinceBootExceptions() {
11129         // good inputs should result in no exceptions.
11130         IStringListener listener = mock(IStringListener.class);
11131         // null listener ==> IllegalArgumentException
11132         assertThrows(IllegalArgumentException.class,
11133                 () -> mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(null));
11134 
11135         // No permission ==> SecurityException
11136         assertThrows(SecurityException.class,
11137                 () -> mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(listener));
11138     }
11139 
11140     @Test
testQueryLastConfiguredTetheredApPassphraseSinceBoot()11141     public void testQueryLastConfiguredTetheredApPassphraseSinceBoot() throws RemoteException {
11142         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
11143         IStringListener listener = mock(IStringListener.class);
11144         String lastPassphrase = "testLastPassphrase";
11145 
11146         InOrder inOrder = inOrder(listener);
11147         when(mWifiApConfigStore.getLastConfiguredTetheredApPassphraseSinceBoot())
11148                 .thenReturn(lastPassphrase);
11149         mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(listener);
11150         mLooper.dispatchAll();
11151         inOrder.verify(listener).onResult(lastPassphrase);
11152 
11153         // Test on null return.
11154         when(mWifiApConfigStore.getLastConfiguredTetheredApPassphraseSinceBoot())
11155                 .thenReturn(null);
11156         mWifiServiceImpl.queryLastConfiguredTetheredApPassphraseSinceBoot(listener);
11157         mLooper.dispatchAll();
11158         inOrder.verify(listener).onResult(null);
11159     }
11160 
11161     @Test
testChannelDataThrowsExceptionsAndOnResult()11162     public void testChannelDataThrowsExceptionsAndOnResult() throws RemoteException {
11163         assumeTrue(SdkLevel.isAtLeastT());
11164         List<Bundle> dataList = new ArrayList<>();
11165         IListListener listener = new IListListener() {
11166             @Override
11167             public void onResult(List value) throws RemoteException {
11168                 dataList.addAll(value);
11169             }
11170             @Override
11171             public IBinder asBinder() {
11172                 return null;
11173             }
11174         };
11175 
11176         //verify listener null case
11177         assertThrows(IllegalArgumentException.class,
11178                 () -> mWifiServiceImpl.getChannelData(null, TEST_PACKAGE_NAME, mExtras));
11179 
11180         when(mScanRequestProxy.getScanResults()).thenReturn(createChannelDataScanResults());
11181         mWifiServiceImpl.getChannelData(listener, TEST_PACKAGE_NAME, mExtras);
11182         mLooper.dispatchAll();
11183 
11184         //verify the result
11185         assertEquals(2, dataList.size());
11186         Bundle dataBundle1 = dataList.get(0);
11187         assertEquals(2412, dataBundle1.getInt(CHANNEL_DATA_KEY_FREQUENCY_MHZ));
11188         assertEquals(1, dataBundle1.getInt(CHANNEL_DATA_KEY_NUM_AP));
11189         Bundle dataBundle2 = dataList.get(1);
11190         assertEquals(5805, dataBundle2.getInt(CHANNEL_DATA_KEY_FREQUENCY_MHZ));
11191         assertEquals(2, dataBundle2.getInt(CHANNEL_DATA_KEY_NUM_AP));
11192 
11193         //verify it will fail without nearby permission
11194         doThrow(new SecurityException()).when(mWifiPermissionsUtil).enforceNearbyDevicesPermission(
11195                 any(), anyBoolean(), any());
11196         assertThrows(SecurityException.class,
11197                 () -> mWifiServiceImpl.getChannelData(listener, TEST_PACKAGE_NAME, mExtras));
11198     }
11199 
11200     /**
11201      * Test register callback without ACCESS_WIFI_STATE permission.
11202      */
11203     @Test
testRegisterLocalOnlyNetworkCallbackWithMissingAccessWifiPermission()11204     public void testRegisterLocalOnlyNetworkCallbackWithMissingAccessWifiPermission() {
11205         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
11206                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
11207         assertThrows(SecurityException.class, () -> mWifiServiceImpl
11208                 .addLocalOnlyConnectionStatusListener(
11209                 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID));
11210     }
11211 
11212     /**
11213      * Test unregister callback without permission.
11214      */
11215     @Test
testUnregisterLocalOnlyNetworkCallbackWithMissingPermission()11216     public void testUnregisterLocalOnlyNetworkCallbackWithMissingPermission() {
11217         doThrow(new SecurityException()).when(mContext).enforceCallingOrSelfPermission(
11218                 eq(ACCESS_WIFI_STATE), eq("WifiService"));
11219         assertThrows(SecurityException.class, () -> mWifiServiceImpl
11220                 .removeLocalOnlyConnectionStatusListener(
11221                         mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME));
11222     }
11223 
11224     /**
11225      * Test register nad unregister callback will go to WifiNetworkSuggestionManager
11226      */
11227     @Test
testRegisterUnregisterLocalOnlyNetworkCallback()11228     public void testRegisterUnregisterLocalOnlyNetworkCallback() throws Exception {
11229         mWifiServiceImpl.addLocalOnlyConnectionStatusListener(
11230                 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME, TEST_FEATURE_ID);
11231         mLooper.dispatchAll();
11232         verify(mWifiNetworkFactory).addLocalOnlyConnectionStatusListener(
11233                 eq(mLocalOnlyConnectionStatusListener), eq(TEST_PACKAGE_NAME), eq(TEST_FEATURE_ID)
11234         );
11235         mWifiServiceImpl.removeLocalOnlyConnectionStatusListener(
11236                 mLocalOnlyConnectionStatusListener, TEST_PACKAGE_NAME);
11237         mLooper.dispatchAll();
11238         verify(mWifiNetworkFactory).removeLocalOnlyConnectionStatusListener(
11239                 eq(mLocalOnlyConnectionStatusListener), eq(TEST_PACKAGE_NAME));
11240     }
11241 
createChannelDataScanResults()11242     private List<ScanResult> createChannelDataScanResults() {
11243         List<ScanResult> scanResults = new ArrayList<>();
11244         scanResults.add(
11245                 new ScanResult(WifiSsid.fromUtf8Text(TEST_SSID), TEST_SSID, TEST_BSSID, 1234, 0,
11246                         TEST_CAP, -78, 2412, 1024, 22, 33, 20, 0, 0, true));
11247         scanResults.add(
11248                 new ScanResult(WifiSsid.fromUtf8Text(TEST_SSID), TEST_SSID, TEST_BSSID, 1234, 0,
11249                         TEST_CAP, -85, 2417, 1024, 22, 33, 20, 0, 0, true));
11250         scanResults.add(
11251                 new ScanResult(WifiSsid.fromUtf8Text(TEST_SSID), TEST_SSID, TEST_BSSID, 1234, 0,
11252                         TEST_CAP, -60, 5805, 1024, 22, 33, 20, 0, 0, true));
11253         scanResults.add(
11254                 new ScanResult(WifiSsid.fromUtf8Text(TEST_SSID), TEST_SSID, TEST_BSSID, 1234, 0,
11255                         TEST_CAP, -70, 5805, 1024, 22, 33, 20, 0, 0, true));
11256         return scanResults;
11257     }
11258 
enableQosPolicyFeature()11259     private void enableQosPolicyFeature() {
11260         when(mApplicationQosPolicyRequestHandler.isFeatureEnabled()).thenReturn(true);
11261         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
11262         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt()))
11263                 .thenReturn(true);
11264     }
11265 
createQosPolicyParamsList(int size, boolean uniqueIds)11266     private List<QosPolicyParams> createQosPolicyParamsList(int size, boolean uniqueIds) {
11267         List<QosPolicyParams> policyParamsList = new ArrayList<>();
11268         for (int i = 0; i < size; i++) {
11269             int policyId = uniqueIds ? i + 2 : 5;
11270             policyParamsList.add(new QosPolicyParams.Builder(
11271                     policyId, QosPolicyParams.DIRECTION_DOWNLINK)
11272                     .setUserPriority(QosPolicyParams.USER_PRIORITY_VIDEO_LOW)
11273                     .setIpVersion(QosPolicyParams.IP_VERSION_4)
11274                     .build());
11275         }
11276         return policyParamsList;
11277     }
11278 
11279     /**
11280      * Verify that addQosPolicies works correctly.
11281      */
11282     @Test
testAddQosPoliciesSuccess()11283     public void testAddQosPoliciesSuccess() throws RemoteException {
11284         assumeTrue(SdkLevel.isAtLeastU());
11285         enableQosPolicyFeature();
11286 
11287         List<QosPolicyParams> paramsList = createQosPolicyParamsList(5, true);
11288         IBinder binder = mock(IBinder.class);
11289         IListListener listener = mock(IListListener.class);
11290         mWifiServiceImpl.addQosPolicies(paramsList, binder, TEST_PACKAGE_NAME, listener);
11291 
11292         mLooper.dispatchAll();
11293         verify(mApplicationQosPolicyRequestHandler).queueAddRequest(
11294                 anyList(), any(), any(), anyInt());
11295     }
11296 
11297     /**
11298      * Verify the expected error cases in addQosPolicies.
11299      */
11300     @Test
testAddQosPoliciesError()11301     public void testAddQosPoliciesError() throws RemoteException {
11302         assumeTrue(SdkLevel.isAtLeastU());
11303         enableQosPolicyFeature();
11304         List<QosPolicyParams> paramsList = createQosPolicyParamsList(5, true);
11305         IBinder binder = mock(IBinder.class);
11306         IListListener listener = mock(IListListener.class);
11307 
11308         // Feature disabled
11309         when(mApplicationQosPolicyRequestHandler.isFeatureEnabled()).thenReturn(false);
11310         mWifiServiceImpl.addQosPolicies(paramsList, binder, TEST_PACKAGE_NAME, listener);
11311         enableQosPolicyFeature();
11312 
11313         verify(listener).onResult(mListCaptor.capture());
11314         List<Integer> statusList = mListCaptor.getValue();
11315         for (Integer status : statusList) {
11316             assertEquals(WifiManager.QOS_REQUEST_STATUS_FAILURE_UNKNOWN, (int) status);
11317         }
11318 
11319         // Null argument
11320         assertThrows(NullPointerException.class, () ->
11321                 mWifiServiceImpl.addQosPolicies(null, binder, TEST_PACKAGE_NAME, listener));
11322         assertThrows(NullPointerException.class, () ->
11323                 mWifiServiceImpl.addQosPolicies(paramsList, null, TEST_PACKAGE_NAME, listener));
11324         assertThrows(NullPointerException.class, () ->
11325                 mWifiServiceImpl.addQosPolicies(paramsList, binder, TEST_PACKAGE_NAME, null));
11326 
11327         // Invalid QoS policy params list
11328         List<QosPolicyParams> emptyList = createQosPolicyParamsList(0, true);
11329         List<QosPolicyParams> largeList = createQosPolicyParamsList(
11330                 WifiManager.getMaxNumberOfPoliciesPerQosRequest() + 1, true);
11331         List<QosPolicyParams> duplicatePolicyList = createQosPolicyParamsList(5, false);
11332         List<QosPolicyParams> mixedDirectionList = createQosPolicyParamsList(1, true);
11333         mixedDirectionList.add(
11334                 new QosPolicyParams.Builder(101, QosPolicyParams.DIRECTION_UPLINK)
11335                         .setDscp(15)
11336                         .build());
11337         assertThrows(IllegalArgumentException.class, () ->
11338                 mWifiServiceImpl.addQosPolicies(emptyList, binder, TEST_PACKAGE_NAME, listener));
11339         assertThrows(IllegalArgumentException.class, () ->
11340                 mWifiServiceImpl.addQosPolicies(largeList, binder, TEST_PACKAGE_NAME, listener));
11341         assertThrows(IllegalArgumentException.class, () ->
11342                 mWifiServiceImpl.addQosPolicies(
11343                         duplicatePolicyList, binder, TEST_PACKAGE_NAME, listener));
11344         assertThrows(IllegalArgumentException.class, () ->
11345                 mWifiServiceImpl.addQosPolicies(
11346                         mixedDirectionList, binder, TEST_PACKAGE_NAME, listener));
11347     }
11348 
11349     /**
11350      * Verify that removeQosPolicies works correctly.
11351      */
11352     @Test
testRemoveQosPoliciesSuccess()11353     public void testRemoveQosPoliciesSuccess() throws RemoteException {
11354         assumeTrue(SdkLevel.isAtLeastU());
11355         enableQosPolicyFeature();
11356 
11357         int[] policyIds = new int[]{1, 2, 3};
11358         mWifiServiceImpl.removeQosPolicies(policyIds, TEST_PACKAGE_NAME);
11359         mLooper.dispatchAll();
11360         verify(mApplicationQosPolicyRequestHandler).queueRemoveRequest(anyList(), anyInt());
11361     }
11362 
11363     /**
11364      * Verify the expected error cases in removeQosPolicies.
11365      */
11366     @Test
testRemoveQosPoliciesError()11367     public void testRemoveQosPoliciesError() {
11368         assumeTrue(SdkLevel.isAtLeastU());
11369         enableQosPolicyFeature();
11370 
11371         // Invalid policy ID list
11372         int[] emptyPolicyIdList = new int[0];
11373         int[] largePolicyIdList = new int[WifiManager.getMaxNumberOfPoliciesPerQosRequest() + 1];
11374         int[] duplicatePolicyIdList = new int[] {1, 2, 2};
11375         assertThrows(NullPointerException.class, () ->
11376                 mWifiServiceImpl.removeQosPolicies(null, TEST_PACKAGE_NAME));
11377         assertThrows(IllegalArgumentException.class, () ->
11378                 mWifiServiceImpl.removeQosPolicies(emptyPolicyIdList, TEST_PACKAGE_NAME));
11379         assertThrows(IllegalArgumentException.class, () ->
11380                 mWifiServiceImpl.removeQosPolicies(largePolicyIdList, TEST_PACKAGE_NAME));
11381         assertThrows(IllegalArgumentException.class, () ->
11382                 mWifiServiceImpl.removeQosPolicies(duplicatePolicyIdList, TEST_PACKAGE_NAME));
11383     }
11384 
11385     /**
11386      * Verify that removeAllQosPolicies works correctly.
11387      */
11388     @Test
testRemoveAllQosPolicies()11389     public void testRemoveAllQosPolicies() {
11390         assumeTrue(SdkLevel.isAtLeastU());
11391         enableQosPolicyFeature();
11392 
11393         mWifiServiceImpl.removeAllQosPolicies(TEST_PACKAGE_NAME);
11394         mLooper.dispatchAll();
11395         verify(mApplicationQosPolicyRequestHandler).queueRemoveAllRequest(anyInt());
11396     }
11397 
11398     /**
11399      * Verify if set / get link layer stats polling interval works correctly
11400      */
11401     @Test
testSetAndGetLinkLayerStatsPollingInterval()11402     public void testSetAndGetLinkLayerStatsPollingInterval() throws Exception {
11403         assumeTrue(SdkLevel.isAtLeastT());
11404         mWifiServiceImpl.setLinkLayerStatsPollingInterval(
11405                 TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS);
11406         mLooper.dispatchAll();
11407         verify(mClientModeManager).setLinkLayerStatsPollingInterval(
11408                 eq(TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS));
11409 
11410         IIntegerListener listener = mock(IIntegerListener.class);
11411         when(mWifiGlobals.getPollRssiIntervalMillis()).thenReturn(
11412                 TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS);
11413         mWifiServiceImpl.getLinkLayerStatsPollingInterval(listener);
11414         mLooper.dispatchAll();
11415         verify(listener).onResult(TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS);
11416     }
11417 
11418     /**
11419      * Test exceptions for set / get link layer stats polling interval
11420      */
11421     @Test
testSetAndGetLinkLayerStatsPollingIntervalThrowsExceptions()11422     public void testSetAndGetLinkLayerStatsPollingIntervalThrowsExceptions() throws Exception {
11423         assumeTrue(SdkLevel.isAtLeastT());
11424         // Verify IllegalArgumentException for negative interval
11425         assertThrows(IllegalArgumentException.class,
11426                 () -> mWifiServiceImpl.setLinkLayerStatsPollingInterval(
11427                         -TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS));
11428         // Verify NullPointerException for null listener
11429         assertThrows(NullPointerException.class,
11430                 () -> mWifiServiceImpl.getLinkLayerStatsPollingInterval(null));
11431         // Verify SecurityException when the caller does not have permission
11432         when(mContext.checkCallingOrSelfPermission(android.Manifest.permission
11433                 .MANAGE_WIFI_NETWORK_SELECTION)).thenReturn(PackageManager.PERMISSION_DENIED);
11434         assertThrows(SecurityException.class,
11435                 () -> mWifiServiceImpl.setLinkLayerStatsPollingInterval(
11436                         TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS));
11437         IIntegerListener listener = mock(IIntegerListener.class);
11438         assertThrows(SecurityException.class,
11439                 () -> mWifiServiceImpl.getLinkLayerStatsPollingInterval(listener));
11440     }
11441 
11442     /**
11443      * Verify {@link WifiServiceImpl#setMloMode(int)}.
11444      */
11445     @Test
testSetMloMode()11446     public void testSetMloMode() throws RemoteException {
11447         // Android U+ only.
11448         assumeTrue(SdkLevel.isAtLeastU());
11449         // Mock listener.
11450         IBooleanListener listener = mock(IBooleanListener.class);
11451         InOrder inOrder = inOrder(listener);
11452 
11453         // Verify permission.
11454         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
11455         assertThrows(SecurityException.class,
11456                 () -> mWifiServiceImpl.setMloMode(WifiManager.MLO_MODE_DEFAULT, listener));
11457         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11458                 true);
11459 
11460         // Verify setMloMode() success.
11461         mWifiThreadRunner.prepareForAutoDispatch();
11462         when(mWifiNative.setMloMode(eq(WifiManager.MLO_MODE_LOW_POWER))).thenReturn(
11463                 WifiStatusCode.SUCCESS);
11464         mWifiServiceImpl.setMloMode(WifiManager.MLO_MODE_LOW_POWER, listener);
11465         mLooper.dispatchAll();
11466         inOrder.verify(listener).onResult(true);
11467 
11468         // Verify setMloMode() failure case.
11469         mWifiThreadRunner.prepareForAutoDispatch();
11470         mLooper.startAutoDispatch();
11471         when(mWifiNative.setMloMode(eq(WifiManager.MLO_MODE_HIGH_THROUGHPUT))).thenReturn(
11472                 WifiStatusCode.ERROR_INVALID_ARGS);
11473         mWifiServiceImpl.setMloMode(WifiManager.MLO_MODE_HIGH_THROUGHPUT, listener);
11474         mLooper.dispatchAll();
11475         inOrder.verify(listener).onResult(false);
11476     }
11477 
11478     /**
11479      * Verify {@link WifiServiceImpl#getMloMode()}.
11480      */
11481     @Test
testGetMloMode()11482     public void testGetMloMode() throws RemoteException {
11483         // Android U+ only.
11484         assumeTrue(SdkLevel.isAtLeastU());
11485         // Mock listener.
11486         IIntegerListener listener = mock(IIntegerListener.class);
11487         InOrder inOrder = inOrder(listener);
11488 
11489         // Verify permission.
11490         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11491                 false);
11492         assertThrows(SecurityException.class,
11493                 () -> mWifiServiceImpl.getMloMode(listener));
11494         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11495                 true);
11496 
11497         // Verify getMloMode() success.
11498         when(mWifiNative.getMloMode()).thenReturn(WifiManager.MLO_MODE_LOW_POWER);
11499         mWifiServiceImpl.getMloMode(listener);
11500         mLooper.dispatchAll();
11501         inOrder.verify(listener).onResult(WifiManager.MLO_MODE_LOW_POWER);
11502     }
11503 
11504     /**
11505      * Verify add and remove of Wi-Fi low latency listener.
11506      */
11507     @Test
testWifiDeviceLowLatencyModeListener()11508     public void testWifiDeviceLowLatencyModeListener() {
11509         // Setup listener.
11510         IWifiLowLatencyLockListener testListener = mock(IWifiLowLatencyLockListener.class);
11511         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(true);
11512         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11513                 true);
11514 
11515         // Test success case.
11516         mWifiServiceImpl.addWifiLowLatencyLockListener(testListener);
11517         mLooper.dispatchAll();
11518         verify(mLockManager).addWifiLowLatencyLockListener(testListener);
11519         mWifiServiceImpl.removeWifiLowLatencyLockListener(testListener);
11520         mLooper.dispatchAll();
11521         verify(mLockManager).removeWifiLowLatencyLockListener(testListener);
11522 
11523         // Test null listener.
11524         assertThrows(IllegalArgumentException.class,
11525                 () -> mWifiServiceImpl.addWifiLowLatencyLockListener(null));
11526         assertThrows(IllegalArgumentException.class,
11527                 () -> mWifiServiceImpl.removeWifiLowLatencyLockListener(null));
11528 
11529         // Expect exception when caller has no permission.
11530         when(mWifiPermissionsUtil.checkNetworkSettingsPermission(anyInt())).thenReturn(false);
11531         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11532                 false);
11533         assertThrows(SecurityException.class,
11534                 () -> mWifiServiceImpl.addWifiLowLatencyLockListener(testListener));
11535 
11536         // No exception for remove.
11537         mWifiServiceImpl.removeWifiLowLatencyLockListener(testListener);
11538     }
11539 
11540     /**
11541      * Verify that setWifiEnabled() returns false when satellite mode is on.
11542      */
11543     @Test
testSetWifiEnabledSatelliteModeOn()11544     public void testSetWifiEnabledSatelliteModeOn() {
11545         when(mSettingsStore.isSatelliteModeOn()).thenReturn(true);
11546         when(mContext.checkPermission(eq(android.Manifest.permission.NETWORK_SETTINGS),
11547                 anyInt(), anyInt())).thenReturn(PackageManager.PERMISSION_GRANTED);
11548         assertFalse(mWifiServiceImpl.setWifiEnabled(TEST_PACKAGE_NAME, true));
11549     }
11550 
11551     /**
11552      * Verify {@link WifiServiceImpl#getMaxMloAssociationLinkCount(IIntegerListener)} and
11553      * {@link WifiServiceImpl#getMaxMloStrLinkCount(IIntegerListener)}.
11554      */
11555     @Test
testGetMloCapabilities()11556     public void testGetMloCapabilities() throws RemoteException {
11557         // Android U+ only.
11558         assumeTrue(SdkLevel.isAtLeastU());
11559         // Mock listener.
11560         IIntegerListener listener = mock(IIntegerListener.class);
11561         InOrder inOrder = inOrder(listener);
11562 
11563         // Verify permission.
11564         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11565                 false);
11566         assertThrows(SecurityException.class,
11567                 () -> mWifiServiceImpl.getMaxMloStrLinkCount(listener, mExtras));
11568         assertThrows(SecurityException.class,
11569                 () -> mWifiServiceImpl.getMaxMloAssociationLinkCount(listener, mExtras));
11570         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11571                 true);
11572 
11573         // verify listener == null.
11574         assertThrows(NullPointerException.class,
11575                 () -> mWifiServiceImpl.getMaxMloStrLinkCount(null, mExtras));
11576         assertThrows(NullPointerException.class,
11577                 () -> mWifiServiceImpl.getMaxMloAssociationLinkCount(null, mExtras));
11578 
11579         // Verify getMaxMloAssociationLinkCount().
11580         when(mWifiNative.getMaxMloAssociationLinkCount(WIFI_IFACE_NAME)).thenReturn(3);
11581         mWifiServiceImpl.getMaxMloAssociationLinkCount(listener, mExtras);
11582         mLooper.dispatchAll();
11583         inOrder.verify(listener).onResult(3);
11584 
11585         // Verify getMaxMloStrLinkCount().
11586         when(mWifiNative.getMaxMloStrLinkCount(WIFI_IFACE_NAME)).thenReturn(2);
11587         mWifiServiceImpl.getMaxMloStrLinkCount(listener, mExtras);
11588         mLooper.dispatchAll();
11589         inOrder.verify(listener).onResult(2);
11590     }
11591 
11592     @Test
testSupportedBandCombinations()11593     public void testSupportedBandCombinations() throws RemoteException {
11594         // Android U+ only.
11595         assumeTrue(SdkLevel.isAtLeastU());
11596         // Mock listener.
11597         IWifiBandsListener listener = mock(IWifiBandsListener.class);
11598         InOrder inOrder = inOrder(listener);
11599 
11600         // Verify permission.
11601         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11602                 false);
11603         assertThrows(SecurityException.class,
11604                 () -> mWifiServiceImpl.getSupportedSimultaneousBandCombinations(listener, mExtras));
11605         when(mWifiPermissionsUtil.checkManageWifiNetworkSelectionPermission(anyInt())).thenReturn(
11606                 true);
11607 
11608         // verify listener == null.
11609         assertThrows(NullPointerException.class,
11610                 () -> mWifiServiceImpl.getSupportedSimultaneousBandCombinations(null, mExtras));
11611 
11612         // verify the behaviour if the band information is not available.
11613         Set<List<Integer>> supportedBandsSet = null;
11614         when(mWifiNative.getSupportedBandCombinations(WIFI_IFACE_NAME)).thenReturn(
11615                 supportedBandsSet);
11616         mWifiServiceImpl.getSupportedSimultaneousBandCombinations(listener, mExtras);
11617         mLooper.dispatchAll();
11618         inOrder.verify(listener).onResult(eq(new WifiBands[0]));
11619 
11620         // Verify positive case.
11621         supportedBandsSet = Set.of(new ArrayList(Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ)),
11622                 new ArrayList(Arrays.asList(WifiScanner.WIFI_BAND_5_GHZ)),
11623                 new ArrayList(Arrays.asList(WifiScanner.WIFI_BAND_6_GHZ)), new ArrayList(
11624                         Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ, WifiScanner.WIFI_BAND_5_GHZ)),
11625                 new ArrayList(
11626                         Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ, WifiScanner.WIFI_BAND_6_GHZ)),
11627                 new ArrayList(
11628                         Arrays.asList(WifiScanner.WIFI_BAND_5_GHZ, WifiScanner.WIFI_BAND_6_GHZ)),
11629                 new ArrayList(
11630                         Arrays.asList(WifiScanner.WIFI_BAND_24_GHZ, WifiScanner.WIFI_BAND_5_GHZ,
11631                                 WifiScanner.WIFI_BAND_6_GHZ)));
11632         when(mWifiNative.getSupportedBandCombinations(WIFI_IFACE_NAME)).thenReturn(
11633                 supportedBandsSet);
11634         mWifiServiceImpl.getSupportedSimultaneousBandCombinations(listener, mExtras);
11635         mLooper.dispatchAll();
11636         ArgumentCaptor<WifiBands[]> resultCaptor = ArgumentCaptor.forClass(WifiBands[].class);
11637         inOrder.verify(listener).onResult(resultCaptor.capture());
11638         int entries = 0;
11639         for (WifiBands band : resultCaptor.getValue()) {
11640             ++entries;
11641             assertTrue(supportedBandsSet.stream().anyMatch(l -> {
11642                 for (int i = 0; i < band.bands.length; ++i) {
11643                     if (i >= l.size()) return false;
11644                     if (band.bands[i] != l.get(i)) return false;
11645                 }
11646                 return true;
11647             }));
11648         }
11649         assertTrue(entries == supportedBandsSet.size());
11650     }
11651 }
11652