1 /*
2  * Copyright (C) 2011 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.net;
18 
19 import static android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS;
20 import static android.Manifest.permission.NETWORK_STACK;
21 import static android.app.ActivityManager.MAX_PROCESS_STATE;
22 import static android.app.ActivityManager.PROCESS_CAPABILITY_ALL;
23 import static android.app.ActivityManager.PROCESS_CAPABILITY_NONE;
24 import static android.app.ActivityManager.PROCESS_CAPABILITY_POWER_RESTRICTED_NETWORK;
25 import static android.app.ActivityManager.PROCESS_CAPABILITY_USER_RESTRICTED_NETWORK;
26 import static android.app.ActivityManager.PROCESS_STATE_IMPORTANT_FOREGROUND;
27 import static android.app.ActivityManager.PROCESS_STATE_LAST_ACTIVITY;
28 import static android.app.ActivityManager.PROCESS_STATE_SERVICE;
29 import static android.app.ActivityManager.PROCESS_STATE_TOP;
30 import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_DATA_SAVER;
31 import static android.net.ConnectivityManager.BLOCKED_METERED_REASON_USER_RESTRICTED;
32 import static android.net.ConnectivityManager.BLOCKED_REASON_APP_BACKGROUND;
33 import static android.net.ConnectivityManager.BLOCKED_REASON_APP_STANDBY;
34 import static android.net.ConnectivityManager.BLOCKED_REASON_BATTERY_SAVER;
35 import static android.net.ConnectivityManager.BLOCKED_REASON_DOZE;
36 import static android.net.ConnectivityManager.BLOCKED_REASON_LOW_POWER_STANDBY;
37 import static android.net.ConnectivityManager.BLOCKED_REASON_NONE;
38 import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
39 import static android.net.ConnectivityManager.FIREWALL_CHAIN_BACKGROUND;
40 import static android.net.ConnectivityManager.FIREWALL_CHAIN_LOW_POWER_STANDBY;
41 import static android.net.ConnectivityManager.FIREWALL_CHAIN_RESTRICTED;
42 import static android.net.ConnectivityManager.TYPE_MOBILE;
43 import static android.net.ConnectivityManager.TYPE_WIFI;
44 import static android.net.INetd.FIREWALL_RULE_ALLOW;
45 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
46 import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
47 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
48 import static android.net.NetworkPolicy.LIMIT_DISABLED;
49 import static android.net.NetworkPolicy.SNOOZE_NEVER;
50 import static android.net.NetworkPolicy.WARNING_DISABLED;
51 import static android.net.NetworkPolicyManager.ALLOWED_METERED_REASON_FOREGROUND;
52 import static android.net.NetworkPolicyManager.ALLOWED_METERED_REASON_SYSTEM;
53 import static android.net.NetworkPolicyManager.ALLOWED_REASON_FOREGROUND;
54 import static android.net.NetworkPolicyManager.ALLOWED_REASON_LOW_POWER_STANDBY_ALLOWLIST;
55 import static android.net.NetworkPolicyManager.ALLOWED_REASON_NONE;
56 import static android.net.NetworkPolicyManager.ALLOWED_REASON_NOT_IN_BACKGROUND;
57 import static android.net.NetworkPolicyManager.ALLOWED_REASON_POWER_SAVE_ALLOWLIST;
58 import static android.net.NetworkPolicyManager.ALLOWED_REASON_POWER_SAVE_EXCEPT_IDLE_ALLOWLIST;
59 import static android.net.NetworkPolicyManager.ALLOWED_REASON_RESTRICTED_MODE_PERMISSIONS;
60 import static android.net.NetworkPolicyManager.ALLOWED_REASON_SYSTEM;
61 import static android.net.NetworkPolicyManager.ALLOWED_REASON_TOP;
62 import static android.net.NetworkPolicyManager.BACKGROUND_THRESHOLD_STATE;
63 import static android.net.NetworkPolicyManager.FIREWALL_RULE_DEFAULT;
64 import static android.net.NetworkPolicyManager.FOREGROUND_THRESHOLD_STATE;
65 import static android.net.NetworkPolicyManager.POLICY_ALLOW_METERED_BACKGROUND;
66 import static android.net.NetworkPolicyManager.POLICY_NONE;
67 import static android.net.NetworkPolicyManager.POLICY_REJECT_METERED_BACKGROUND;
68 import static android.net.NetworkPolicyManager.TOP_THRESHOLD_STATE;
69 import static android.net.NetworkPolicyManager.allowedReasonsToString;
70 import static android.net.NetworkPolicyManager.blockedReasonsToString;
71 import static android.net.NetworkPolicyManager.uidPoliciesToString;
72 import static android.net.NetworkPolicyManager.uidRulesToString;
73 import static android.net.NetworkStack.PERMISSION_MAINLINE_NETWORK_STACK;
74 import static android.net.NetworkStats.METERED_NO;
75 import static android.net.NetworkStats.METERED_YES;
76 import static android.net.NetworkTemplate.MATCH_CARRIER;
77 import static android.net.NetworkTemplate.MATCH_MOBILE;
78 import static android.net.NetworkTemplate.MATCH_WIFI;
79 import static android.os.PowerExemptionManager.REASON_OTHER;
80 import static android.telephony.CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED;
81 import static android.telephony.CarrierConfigManager.DATA_CYCLE_THRESHOLD_DISABLED;
82 import static android.telephony.CarrierConfigManager.DATA_CYCLE_USE_PLATFORM_DEFAULT;
83 import static android.telephony.CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG;
84 import static android.telephony.CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG;
85 import static android.telephony.CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT;
86 import static android.telephony.SubscriptionPlan.BYTES_UNLIMITED;
87 import static android.telephony.SubscriptionPlan.LIMIT_BEHAVIOR_DISABLED;
88 
89 import static com.android.server.net.NetworkPolicyManagerInternal.QUOTA_TYPE_JOBS;
90 import static com.android.server.net.NetworkPolicyManagerInternal.QUOTA_TYPE_MULTIPATH;
91 import static com.android.server.net.NetworkPolicyManagerService.OPPORTUNISTIC_QUOTA_UNKNOWN;
92 import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT;
93 import static com.android.server.net.NetworkPolicyManagerService.TYPE_LIMIT_SNOOZED;
94 import static com.android.server.net.NetworkPolicyManagerService.TYPE_RAPID;
95 import static com.android.server.net.NetworkPolicyManagerService.TYPE_WARNING;
96 import static com.android.server.net.NetworkPolicyManagerService.UID_MSG_STATE_CHANGED;
97 import static com.android.server.net.NetworkPolicyManagerService.UidBlockedState.getEffectiveBlockedReasons;
98 import static com.android.server.net.NetworkPolicyManagerService.normalizeTemplate;
99 
100 import static org.junit.Assert.assertEquals;
101 import static org.junit.Assert.assertFalse;
102 import static org.junit.Assert.assertNotNull;
103 import static org.junit.Assert.assertNull;
104 import static org.junit.Assert.assertTrue;
105 import static org.junit.Assert.fail;
106 import static org.mockito.ArgumentMatchers.any;
107 import static org.mockito.ArgumentMatchers.anyBoolean;
108 import static org.mockito.ArgumentMatchers.anyInt;
109 import static org.mockito.ArgumentMatchers.anyLong;
110 import static org.mockito.ArgumentMatchers.anyString;
111 import static org.mockito.ArgumentMatchers.eq;
112 import static org.mockito.ArgumentMatchers.isA;
113 import static org.mockito.Mockito.CALLS_REAL_METHODS;
114 import static org.mockito.Mockito.atLeast;
115 import static org.mockito.Mockito.atLeastOnce;
116 import static org.mockito.Mockito.clearInvocations;
117 import static org.mockito.Mockito.doAnswer;
118 import static org.mockito.Mockito.doNothing;
119 import static org.mockito.Mockito.mock;
120 import static org.mockito.Mockito.never;
121 import static org.mockito.Mockito.reset;
122 import static org.mockito.Mockito.times;
123 import static org.mockito.Mockito.verify;
124 import static org.mockito.Mockito.when;
125 
126 import android.Manifest;
127 import android.app.ActivityManager;
128 import android.app.ActivityManagerInternal;
129 import android.app.IActivityManager;
130 import android.app.IUidObserver;
131 import android.app.Notification;
132 import android.app.NotificationManager;
133 import android.app.usage.NetworkStats;
134 import android.app.usage.NetworkStatsManager;
135 import android.app.usage.UsageStatsManagerInternal;
136 import android.content.BroadcastReceiver;
137 import android.content.Context;
138 import android.content.Intent;
139 import android.content.IntentFilter;
140 import android.content.pm.ApplicationInfo;
141 import android.content.pm.IPackageManager;
142 import android.content.pm.PackageInfo;
143 import android.content.pm.PackageManager;
144 import android.content.pm.PackageManagerInternal;
145 import android.content.pm.Signature;
146 import android.content.pm.UserInfo;
147 import android.net.ConnectivityManager;
148 import android.net.INetworkManagementEventObserver;
149 import android.net.INetworkPolicyListener;
150 import android.net.LinkProperties;
151 import android.net.Network;
152 import android.net.NetworkCapabilities;
153 import android.net.NetworkPolicy;
154 import android.net.NetworkPolicyManager;
155 import android.net.NetworkStateSnapshot;
156 import android.net.NetworkTemplate;
157 import android.net.TelephonyNetworkSpecifier;
158 import android.net.wifi.WifiInfo;
159 import android.os.Binder;
160 import android.os.Build;
161 import android.os.Handler;
162 import android.os.INetworkManagementService;
163 import android.os.PersistableBundle;
164 import android.os.PowerExemptionManager;
165 import android.os.PowerManager;
166 import android.os.PowerManagerInternal;
167 import android.os.PowerSaveState;
168 import android.os.RemoteException;
169 import android.os.SimpleClock;
170 import android.os.SystemClock;
171 import android.os.UserHandle;
172 import android.os.UserManager;
173 import android.platform.test.annotations.Presubmit;
174 import android.platform.test.annotations.RequiresFlagsDisabled;
175 import android.platform.test.annotations.RequiresFlagsEnabled;
176 import android.platform.test.flag.junit.CheckFlagsRule;
177 import android.platform.test.flag.junit.DeviceFlagsValueProvider;
178 import android.telephony.CarrierConfigManager;
179 import android.telephony.SubscriptionInfo;
180 import android.telephony.SubscriptionManager;
181 import android.telephony.SubscriptionPlan;
182 import android.telephony.TelephonyCallback;
183 import android.telephony.TelephonyManager;
184 import android.text.TextUtils;
185 import android.util.ArrayMap;
186 import android.util.ArraySet;
187 import android.util.DataUnit;
188 import android.util.Log;
189 import android.util.Pair;
190 import android.util.Range;
191 import android.util.RecurrenceRule;
192 import android.util.SparseArray;
193 import android.util.SparseIntArray;
194 
195 import androidx.test.InstrumentationRegistry;
196 import androidx.test.filters.FlakyTest;
197 import androidx.test.filters.MediumTest;
198 import androidx.test.runner.AndroidJUnit4;
199 
200 import com.android.internal.util.test.BroadcastInterceptingContext;
201 import com.android.internal.util.test.BroadcastInterceptingContext.FutureIntent;
202 import com.android.internal.util.test.FsUtil;
203 import com.android.server.DeviceIdleInternal;
204 import com.android.server.LocalServices;
205 import com.android.server.pm.pkg.AndroidPackage;
206 import com.android.server.usage.AppStandbyInternal;
207 
208 import libcore.io.Streams;
209 
210 import org.junit.After;
211 import org.junit.Assume;
212 import org.junit.Before;
213 import org.junit.Rule;
214 import org.junit.Test;
215 import org.junit.rules.MethodRule;
216 import org.junit.runner.RunWith;
217 import org.junit.runners.model.FrameworkMethod;
218 import org.junit.runners.model.Statement;
219 import org.mockito.ArgumentCaptor;
220 import org.mockito.Mock;
221 import org.mockito.MockitoAnnotations;
222 import org.mockito.invocation.InvocationOnMock;
223 import org.mockito.stubbing.Answer;
224 
225 import java.io.File;
226 import java.io.FileOutputStream;
227 import java.io.InputStream;
228 import java.io.OutputStream;
229 import java.lang.annotation.Annotation;
230 import java.lang.annotation.ElementType;
231 import java.lang.annotation.Retention;
232 import java.lang.annotation.RetentionPolicy;
233 import java.lang.annotation.Target;
234 import java.time.Clock;
235 import java.time.Instant;
236 import java.time.Period;
237 import java.time.ZoneId;
238 import java.time.ZoneOffset;
239 import java.time.ZonedDateTime;
240 import java.util.ArrayList;
241 import java.util.Arrays;
242 import java.util.Calendar;
243 import java.util.HashMap;
244 import java.util.Iterator;
245 import java.util.LinkedHashSet;
246 import java.util.List;
247 import java.util.Map;
248 import java.util.Set;
249 import java.util.TimeZone;
250 import java.util.concurrent.CountDownLatch;
251 import java.util.concurrent.Future;
252 import java.util.concurrent.TimeUnit;
253 import java.util.function.Consumer;
254 import java.util.stream.Collectors;
255 
256 /**
257  * Tests for {@link NetworkPolicyManagerService}.
258  */
259 @RunWith(AndroidJUnit4.class)
260 @MediumTest
261 @Presubmit
262 public class NetworkPolicyManagerServiceTest {
263     private static final String TAG = "NetworkPolicyManagerServiceTest";
264 
265     @Rule
266     public final CheckFlagsRule mCheckFlagsRule = DeviceFlagsValueProvider.createCheckFlagsRule();
267 
268     private static final long TEST_START = 1194220800000L;
269     private static final String TEST_IFACE = "test0";
270     private static final String TEST_WIFI_NETWORK_KEY = "TestWifiNetworkKey";
271     private static final String TEST_IMSI = "310210";
272     private static final int TEST_SUB_ID = 42;
273     private static final int TEST_SUB_ID2 = 24;
274     private static final Network TEST_NETWORK = mock(Network.class, CALLS_REAL_METHODS);
275 
276     private static NetworkTemplate sTemplateWifi = new NetworkTemplate.Builder(MATCH_WIFI)
277             .setWifiNetworkKeys(Set.of(TEST_WIFI_NETWORK_KEY)).build();
278     private static NetworkTemplate sTemplateCarrierMetered =
279             new NetworkTemplate.Builder(MATCH_CARRIER)
280                     .setSubscriberIds(Set.of(TEST_IMSI))
281                     .setMeteredness(METERED_YES).build();
282 
283     /**
284      * Path on assets where files used by {@link NetPolicyXml} are located.
285      */
286     private static final String NETPOLICY_DIR = "NetworkPolicyManagerServiceTest/netpolicy";
287     private static final String TIMEZONE_UTC = "UTC";
288 
289     private BroadcastInterceptingContext mServiceContext;
290     private File mPolicyDir;
291 
292     /**
293      * Relative path of the XML file that will be used as {@code netpolicy.xml}.
294      *
295      * <p>Typically set through a {@link NetPolicyXml} annotation in the test method.
296      */
297     private String mNetpolicyXml;
298 
299     private @Mock IActivityManager mActivityManager;
300     private @Mock INetworkManagementService mNetworkManager;
301     private @Mock ConnectivityManager mConnManager;
302     private @Mock NotificationManager mNotifManager;
303     private @Mock PackageManager mPackageManager;
304     private @Mock IPackageManager mIpm;
305     private @Mock SubscriptionManager mSubscriptionManager;
306     private @Mock CarrierConfigManager mCarrierConfigManager;
307     private @Mock TelephonyManager mTelephonyManager;
308     private @Mock UserManager mUserManager;
309     private @Mock NetworkStatsManager mStatsManager;
310     private @Mock PowerExemptionManager mPowerExemptionManager;
311     private TestDependencies mDeps;
312 
313     private ArgumentCaptor<ConnectivityManager.NetworkCallback> mNetworkCallbackCaptor =
314             ArgumentCaptor.forClass(ConnectivityManager.NetworkCallback.class);
315 
316     private TelephonyCallback.ActiveDataSubscriptionIdListener mActiveDataSubIdListener;
317 
318     private ActivityManagerInternal mActivityManagerInternal;
319     private PackageManagerInternal mPackageManagerInternal;
320 
321     private IUidObserver mUidObserver;
322     private INetworkManagementEventObserver mNetworkObserver;
323 
324     private NetworkPolicyListenerAnswer mPolicyListener;
325     private NetworkPolicyManagerService mService;
326 
327     private final ArraySet<BroadcastReceiver> mRegisteredReceivers = new ArraySet<>();
328     private BroadcastReceiver mPowerAllowlistReceiver;
329 
330     /**
331      * In some of the tests while initializing NetworkPolicyManagerService,
332      * ACTION_RESTRICT_BACKGROUND_CHANGED is broadcasted. This is for capturing that broadcast.
333      */
334     private FutureIntent mFutureIntent;
335 
336     private long mStartTime;
337     private long mElapsedRealtime;
338 
339     private static final int USER_ID = 0;
340     private static final int FAKE_SUB_ID = 3737373;
341     private static final String FAKE_SUBSCRIBER_ID = "FAKE_SUBSCRIBER_ID";
342     private static final int DEFAULT_CYCLE_DAY = 1;
343     private static final int INVALID_CARRIER_CONFIG_VALUE = -9999;
344     private long mDefaultWarningBytes; // filled in with the actual default before tests are run
345     private long mDefaultLimitBytes; // filled in with the actual default before tests are run
346     private PersistableBundle mCarrierConfig = CarrierConfigManager.getDefaultConfig();
347 
348     private static final int APP_ID_A = android.os.Process.FIRST_APPLICATION_UID + 4;
349     private static final int APP_ID_B = android.os.Process.FIRST_APPLICATION_UID + 8;
350     private static final int APP_ID_C = android.os.Process.FIRST_APPLICATION_UID + 15;
351     private static final int APP_ID_D = android.os.Process.FIRST_APPLICATION_UID + 16;
352     private static final int APP_ID_E = android.os.Process.FIRST_APPLICATION_UID + 23;
353     private static final int APP_ID_F = android.os.Process.FIRST_APPLICATION_UID + 42;
354 
355     private static final int UID_A = UserHandle.getUid(USER_ID, APP_ID_A);
356     private static final int UID_B = UserHandle.getUid(USER_ID, APP_ID_B);
357     private static final int UID_C = UserHandle.getUid(USER_ID, APP_ID_C);
358     private static final int UID_D = UserHandle.getUid(USER_ID, APP_ID_D);
359     private static final int UID_E = UserHandle.getUid(USER_ID, APP_ID_E);
360     private static final int UID_F = UserHandle.getUid(USER_ID, APP_ID_F);
361 
362     private static final String PKG_NAME_A = "name.is.A,pkg.A";
363     private static final String PKG_NAME_B = "name.is.B,pkg.B";
364     private static final String PKG_NAME_C = "name.is.C,pkg.C";
365 
366     public final @Rule NetPolicyMethodRule mNetPolicyXmlRule = new NetPolicyMethodRule();
367 
368     private final Clock mClock = new SimpleClock(ZoneOffset.UTC) {
369         @Override
370         public long millis() {
371             return currentTimeMillis();
372         }
373     };
374 
registerLocalServices()375     private void registerLocalServices() {
376         addLocalServiceMock(DeviceIdleInternal.class);
377         addLocalServiceMock(AppStandbyInternal.class);
378 
379         final UsageStatsManagerInternal usageStats =
380                 addLocalServiceMock(UsageStatsManagerInternal.class);
381         when(usageStats.getIdleUidsForUser(anyInt())).thenReturn(new int[]{});
382 
383         mActivityManagerInternal = addLocalServiceMock(ActivityManagerInternal.class);
384         mPackageManagerInternal = addLocalServiceMock(PackageManagerInternal.class);
385 
386         final PowerSaveState state = new PowerSaveState.Builder()
387                 .setBatterySaverEnabled(false).build();
388         final PowerManagerInternal pmInternal = addLocalServiceMock(PowerManagerInternal.class);
389         when(pmInternal.getLowPowerState(anyInt())).thenReturn(state);
390     }
391 
392     private class TestDependencies extends NetworkPolicyManagerService.Dependencies {
393         private final SparseArray<NetworkStats.Bucket> mMockedStats = new SparseArray<>();
394         private int mMockDefaultDataSubId;
395         private int mMockedActiveDataSubId;
396 
TestDependencies(Context context)397         TestDependencies(Context context) {
398             super(context);
399         }
400 
401         @Override
getNetworkTotalBytes(NetworkTemplate template, long start, long end)402         long getNetworkTotalBytes(NetworkTemplate template, long start, long end) {
403             int total = 0;
404             for (int i = 0; i < mMockedStats.size(); i++) {
405                 NetworkStats.Bucket bucket = mMockedStats.valueAt(i);
406                 total += bucket.getRxBytes() + bucket.getTxBytes();
407             }
408             return total;
409         }
410 
411         @Override
getNetworkUidBytes(NetworkTemplate template, long start, long end)412         List<NetworkStats.Bucket> getNetworkUidBytes(NetworkTemplate template, long start,
413                 long end) {
414             final List<NetworkStats.Bucket> ret = new ArrayList<>();
415             for (int i = 0; i < mMockedStats.size(); i++) {
416                 ret.add(mMockedStats.valueAt(i));
417             }
418             return ret;
419         }
420 
setMockedTotalBytes(int uid, long rxBytes, long txBytes)421         private void setMockedTotalBytes(int uid, long rxBytes, long txBytes) {
422             final NetworkStats.Bucket bucket = mock(NetworkStats.Bucket.class);
423             when(bucket.getUid()).thenReturn(uid);
424             when(bucket.getRxBytes()).thenReturn(rxBytes);
425             when(bucket.getTxBytes()).thenReturn(txBytes);
426             mMockedStats.set(uid, bucket);
427         }
428 
increaseMockedTotalBytes(int uid, long rxBytes, long txBytes)429         private void increaseMockedTotalBytes(int uid, long rxBytes, long txBytes) {
430             final NetworkStats.Bucket bucket = mMockedStats.get(uid);
431             setMockedTotalBytes(uid, bucket.getRxBytes() + rxBytes, bucket.getTxBytes() + txBytes);
432         }
433 
setDefaultAndActiveDataSubId(int defaultDataSubId, int activeDataSubId)434         void setDefaultAndActiveDataSubId(int defaultDataSubId, int activeDataSubId) {
435             mMockDefaultDataSubId = defaultDataSubId;
436             mMockedActiveDataSubId = activeDataSubId;
437         }
438 
439         @Override
getDefaultDataSubId()440         int getDefaultDataSubId() {
441             return mMockDefaultDataSubId;
442         }
443 
444         @Override
getActivateDataSubId()445         int getActivateDataSubId() {
446             return mMockedActiveDataSubId;
447         }
448     }
449 
450     // TODO: Use TestLooperManager instead.
451     /**
452      * Helper that leverages try-with-resources to pause dispatch of
453      * {@link #mHandlerThread} until released.
454      */
455     static class SyncBarrier implements AutoCloseable {
456         private final int mToken;
457         private Handler mHandler;
458 
SyncBarrier(Handler handler)459         SyncBarrier(Handler handler) {
460             mHandler = handler;
461             mToken = mHandler.getLooper().getQueue().postSyncBarrier();
462         }
463 
464         @Override
close()465         public void close() throws Exception {
466             mHandler.getLooper().getQueue().removeSyncBarrier(mToken);
467         }
468     }
469 
470     @Before
callSystemReady()471     public void callSystemReady() throws Exception {
472         MockitoAnnotations.initMocks(this);
473         when(mPowerExemptionManager.getAllowListedAppIds(anyBoolean())).thenReturn(new int[0]);
474 
475         final Context context = InstrumentationRegistry.getContext();
476 
477         setCurrentTimeMillis(TEST_START);
478 
479         registerLocalServices();
480         // Intercept various broadcasts, and pretend that uids have packages.
481         // Also return mock service instances for a few critical services.
482         mServiceContext = new BroadcastInterceptingContext(context) {
483             @Override
484             public PackageManager getPackageManager() {
485                 return mPackageManager;
486             }
487 
488             @Override
489             public void startActivity(Intent intent) {
490                 // ignored
491             }
492 
493             @Override
494             public Object getSystemService(String name) {
495                 switch (name) {
496                     case Context.TELEPHONY_SUBSCRIPTION_SERVICE:
497                         return mSubscriptionManager;
498                     case Context.CARRIER_CONFIG_SERVICE:
499                         return mCarrierConfigManager;
500                     case Context.TELEPHONY_SERVICE:
501                         return mTelephonyManager;
502                     case Context.NOTIFICATION_SERVICE:
503                         return mNotifManager;
504                     case Context.CONNECTIVITY_SERVICE:
505                         return mConnManager;
506                     case Context.USER_SERVICE:
507                         return mUserManager;
508                     case Context.NETWORK_STATS_SERVICE:
509                         return mStatsManager;
510                     case Context.POWER_EXEMPTION_SERVICE:
511                         return mPowerExemptionManager;
512                     default:
513                         return super.getSystemService(name);
514                 }
515             }
516 
517             @Override
518             public void enforceCallingOrSelfPermission(String permission, String message) {
519                 // Assume that we're AID_SYSTEM
520             }
521 
522             @Override
523             public Intent registerReceiver(BroadcastReceiver receiver,
524                     IntentFilter filter, String broadcastPermission, Handler scheduler) {
525                 if (filter.hasAction(PowerManager.ACTION_POWER_SAVE_WHITELIST_CHANGED)) {
526                     mPowerAllowlistReceiver = receiver;
527                 }
528                 mRegisteredReceivers.add(receiver);
529                 return super.registerReceiver(receiver, filter, broadcastPermission, scheduler);
530             }
531 
532             @Override
533             public Intent registerReceiverForAllUsers(BroadcastReceiver receiver,
534                     IntentFilter filter, String broadcastPermission, Handler scheduler) {
535                 mRegisteredReceivers.add(receiver);
536                 return super.registerReceiverForAllUsers(receiver, filter, broadcastPermission,
537                         scheduler);
538             }
539         };
540 
541         setNetpolicyXml(context);
542 
543         doAnswer(new Answer<Void>() {
544             @Override
545             public Void answer(InvocationOnMock invocation) throws Throwable {
546                 mUidObserver = (IUidObserver) invocation.getArguments()[0];
547                 Log.d(TAG, "set mUidObserver to " + mUidObserver);
548                 return null;
549             }
550         }).when(mActivityManagerInternal).registerNetworkPolicyUidObserver(any(),
551                 anyInt(), anyInt(), any(String.class));
552 
553         mFutureIntent = newRestrictBackgroundChangedFuture();
554         mDeps = new TestDependencies(mServiceContext);
555         mService = new NetworkPolicyManagerService(mServiceContext, mActivityManager,
556                 mNetworkManager, mIpm, mClock, mPolicyDir, true, mDeps);
557         mService.bindConnectivityManager();
558         mPolicyListener = new NetworkPolicyListenerAnswer(mService);
559 
560         // Sets some common expectations.
561         when(mPackageManager.getPackageInfo(anyString(), anyInt())).thenAnswer(
562                 new Answer<PackageInfo>() {
563 
564                     @Override
565                     public PackageInfo answer(InvocationOnMock invocation) throws Throwable {
566                         final String packageName = (String) invocation.getArguments()[0];
567                         final PackageInfo info = new PackageInfo();
568                         final Signature signature;
569                         if ("android".equals(packageName)) {
570                             signature = new Signature("F00D");
571                         } else {
572                             signature = new Signature("DEAD");
573                         }
574                         info.signatures = new Signature[] {
575                             signature
576                         };
577                         return info;
578                     }
579                 });
580         when(mPackageManager.getApplicationInfoAsUser(anyString(), anyInt(), anyInt()))
581                 .thenReturn(new ApplicationInfo());
582         when(mPackageManager.getPackagesForUid(UID_A)).thenReturn(new String[] {PKG_NAME_A});
583         when(mPackageManager.getPackagesForUid(UID_B)).thenReturn(new String[] {PKG_NAME_B});
584         when(mPackageManager.getPackagesForUid(UID_C)).thenReturn(new String[] {PKG_NAME_C});
585         when(mPackageManager.getApplicationInfo(eq(PKG_NAME_A), anyInt()))
586                 .thenReturn(buildApplicationInfo(PKG_NAME_A, UID_A));
587         when(mPackageManager.getApplicationInfo(eq(PKG_NAME_B), anyInt()))
588                 .thenReturn(buildApplicationInfo(PKG_NAME_B, UID_B));
589         when(mPackageManager.getApplicationInfo(eq(PKG_NAME_C), anyInt()))
590                 .thenReturn(buildApplicationInfo(PKG_NAME_C, UID_C));
591         doAnswer(arg -> {
592             final Consumer<AndroidPackage> consumer =
593                     (Consumer<AndroidPackage>) arg.getArguments()[0];
594             for (AndroidPackage androidPackage : buildInstalledPackageList()) {
595                 consumer.accept(androidPackage);
596             }
597             return null;
598         }).when(mPackageManagerInternal).forEachInstalledPackage(
599                 any(Consumer.class), anyInt());
600         when(mUserManager.getUsers()).thenReturn(buildUserInfoList());
601         when(mNetworkManager.isBandwidthControlEnabled()).thenReturn(true);
602         when(mNetworkManager.setDataSaverModeEnabled(anyBoolean())).thenReturn(true);
603         doNothing().when(mConnManager)
604                 .registerNetworkCallback(any(), mNetworkCallbackCaptor.capture());
605 
606         // Create the expected carrier config
607         mCarrierConfig.putBoolean(CarrierConfigManager.KEY_CARRIER_CONFIG_APPLIED_BOOL, true);
608 
609         // Prepare NPMS.
610         mService.systemReady(mService.networkScoreAndNetworkManagementServiceReady());
611 
612         // catch INetworkManagementEventObserver during systemReady()
613         final ArgumentCaptor<INetworkManagementEventObserver> networkObserver =
614                 ArgumentCaptor.forClass(INetworkManagementEventObserver.class);
615         verify(mNetworkManager).registerObserver(networkObserver.capture());
616         mNetworkObserver = networkObserver.getValue();
617 
618         // Catch UsageCallback during systemReady(). Simulate NetworkStatsService triggered
619         // stats updated callback to signal its readiness.
620         final ArgumentCaptor<NetworkStatsManager.UsageCallback> usageObserver =
621                 ArgumentCaptor.forClass(NetworkStatsManager.UsageCallback.class);
622         verify(mStatsManager, times(2))
623                 .registerUsageCallback(any(), anyLong(), any(), usageObserver.capture());
624         // It doesn't matter which of the observers is returned here.
625         usageObserver.getValue().onThresholdReached(
626                 new NetworkTemplate.Builder(MATCH_MOBILE).build());
627 
628         NetworkPolicy defaultPolicy = mService.buildDefaultCarrierPolicy(0, "");
629         mDefaultWarningBytes = defaultPolicy.warningBytes;
630         mDefaultLimitBytes = defaultPolicy.limitBytes;
631 
632         // Catch TelephonyCallback during systemReady().
633         ArgumentCaptor<TelephonyCallback> telephonyCallbackArgumentCaptor =
634                 ArgumentCaptor.forClass(TelephonyCallback.class);
635         verify(mTelephonyManager).registerTelephonyCallback(any(),
636                 telephonyCallbackArgumentCaptor.capture());
637         mActiveDataSubIdListener = (TelephonyCallback.ActiveDataSubscriptionIdListener)
638                 telephonyCallbackArgumentCaptor.getValue();
639     }
640 
641     @After
removeFiles()642     public void removeFiles() throws Exception {
643         for (File file : mPolicyDir.listFiles()) {
644             file.delete();
645         }
646     }
647 
648     @After
unregisterLocalServices()649     public void unregisterLocalServices() throws Exception {
650         // Registered by NetworkPolicyManagerService's constructor.
651         LocalServices.removeServiceForTest(NetworkPolicyManagerInternal.class);
652 
653         // Added in registerLocalServices()
654         LocalServices.removeServiceForTest(ActivityManagerInternal.class);
655         LocalServices.removeServiceForTest(PowerManagerInternal.class);
656         LocalServices.removeServiceForTest(DeviceIdleInternal.class);
657         LocalServices.removeServiceForTest(AppStandbyInternal.class);
658         LocalServices.removeServiceForTest(UsageStatsManagerInternal.class);
659         LocalServices.removeServiceForTest(PackageManagerInternal.class);
660     }
661 
662     @After
resetClock()663     public void resetClock() throws Exception {
664         RecurrenceRule.sClock = Clock.systemDefaultZone();
665     }
666 
667     @After
unregisterReceivers()668     public void unregisterReceivers() throws Exception {
669         for (BroadcastReceiver receiver : mRegisteredReceivers) {
670             mServiceContext.unregisterReceiver(receiver);
671         }
672     }
673 
674     @Test
testTurnRestrictBackgroundOn()675     public void testTurnRestrictBackgroundOn() throws Exception {
676         assertRestrictBackgroundOff();
677         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
678         setRestrictBackground(true);
679         assertRestrictBackgroundChangedReceived(futureIntent, null);
680     }
681 
682     @Test
683     @NetPolicyXml("restrict-background-on.xml")
testTurnRestrictBackgroundOff()684     public void testTurnRestrictBackgroundOff() throws Exception {
685         assertRestrictBackgroundOn();
686         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
687         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
688         setRestrictBackground(false);
689         assertRestrictBackgroundChangedReceived(futureIntent, null);
690     }
691 
692     /**
693      * Adds an app to allowlist when restrict background is on - app should receive an intent.
694      */
695     @Test
696     @NetPolicyXml("restrict-background-on.xml")
testAddRestrictBackgroundAllowlist_restrictBackgroundOn()697     public void testAddRestrictBackgroundAllowlist_restrictBackgroundOn() throws Exception {
698         assertRestrictBackgroundOn();
699         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
700         addRestrictBackgroundAllowlist(true);
701     }
702 
703     /**
704      * Adds an app to allowlist when restrict background is off - app should not receive an intent.
705      */
706     @Test
testAddRestrictBackgroundAllowlist_restrictBackgroundOff()707     public void testAddRestrictBackgroundAllowlist_restrictBackgroundOff() throws Exception {
708         assertRestrictBackgroundOff();
709         addRestrictBackgroundAllowlist(false);
710     }
711 
addRestrictBackgroundAllowlist(boolean expectIntent)712     private void addRestrictBackgroundAllowlist(boolean expectIntent) throws Exception {
713         assertRestrictBackgroundAllowedUids();
714         assertUidPolicy(UID_A, POLICY_NONE);
715 
716         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
717         mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
718 
719         mService.setUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
720 
721         assertRestrictBackgroundAllowedUids(UID_A);
722         assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
723         mPolicyListener.waitAndVerify()
724                 .onUidPoliciesChanged(APP_ID_A, POLICY_ALLOW_METERED_BACKGROUND);
725         if (expectIntent) {
726             assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
727         } else {
728             futureIntent.assertNotReceived();
729         }
730     }
731 
732     /**
733      * Removes an app from allowlist when restrict background is on - app should receive an intent.
734      */
735     @Test
736     @NetPolicyXml("uidA-allowed-restrict-background-on.xml")
testRemoveRestrictBackgroundAllowlist_restrictBackgroundOn()737     public void testRemoveRestrictBackgroundAllowlist_restrictBackgroundOn() throws Exception {
738         assertRestrictBackgroundOn();
739         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
740         removeRestrictBackgroundAllowlist(true);
741     }
742 
743     /**
744      * Removes an app from allowlist when restrict background is off - app should not
745      * receive an intent.
746      */
747     @Test
748     @NetPolicyXml("uidA-allowed-restrict-background-off.xml")
testRemoveRestrictBackgroundAllowlist_restrictBackgroundOff()749     public void testRemoveRestrictBackgroundAllowlist_restrictBackgroundOff() throws Exception {
750         assertRestrictBackgroundOff();
751         removeRestrictBackgroundAllowlist(false);
752     }
753 
754     @Test
testLowPowerModeObserver_ListenersRegistered()755     public void testLowPowerModeObserver_ListenersRegistered()
756             throws Exception {
757         PowerManagerInternal pmInternal = LocalServices.getService(PowerManagerInternal.class);
758 
759         verify(pmInternal, atLeast(2)).registerLowPowerModeObserver(any());
760     }
761 
762     @Test
updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()763     public void updateRestrictBackgroundByLowPowerMode_RestrictOnBeforeBsm_RestrictOnAfterBsm()
764             throws Exception {
765         setRestrictBackground(true);
766         PowerSaveState stateOn = new PowerSaveState.Builder()
767                 .setGlobalBatterySaverEnabled(true)
768                 .setBatterySaverEnabled(false)
769                 .build();
770         mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
771 
772         // RestrictBackground should be on even though battery saver want to turn it off
773         assertTrue(mService.getRestrictBackground());
774 
775         PowerSaveState stateOff = new PowerSaveState.Builder()
776                 .setGlobalBatterySaverEnabled(false)
777                 .setBatterySaverEnabled(false)
778                 .build();
779         mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
780 
781         // RestrictBackground should be on, as before.
782         assertTrue(mService.getRestrictBackground());
783 
784         stateOn = new PowerSaveState.Builder()
785                 .setGlobalBatterySaverEnabled(true)
786                 .setBatterySaverEnabled(true)
787                 .build();
788         mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
789 
790         // RestrictBackground should be on.
791         assertTrue(mService.getRestrictBackground());
792 
793         stateOff = new PowerSaveState.Builder()
794                 .setGlobalBatterySaverEnabled(false)
795                 .setBatterySaverEnabled(false)
796                 .build();
797         mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
798 
799         // RestrictBackground should be on, as it was enabled manually before battery saver.
800         assertTrue(mService.getRestrictBackground());
801     }
802 
803     @Test
updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()804     public void updateRestrictBackgroundByLowPowerMode_RestrictOffBeforeBsm_RestrictOffAfterBsm()
805             throws Exception {
806         setRestrictBackground(false);
807         PowerSaveState stateOn = new PowerSaveState.Builder()
808                 .setGlobalBatterySaverEnabled(true)
809                 .setBatterySaverEnabled(true)
810                 .build();
811 
812         mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
813 
814         // RestrictBackground should be turned on because of battery saver
815         assertTrue(mService.getRestrictBackground());
816 
817         PowerSaveState stateOff = new PowerSaveState.Builder()
818                 .setGlobalBatterySaverEnabled(false)
819                 .setBatterySaverEnabled(false)
820                 .build();
821         mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
822 
823         // RestrictBackground should be off, following its previous state
824         assertFalse(mService.getRestrictBackground());
825 
826         PowerSaveState stateOnRestrictOff = new PowerSaveState.Builder()
827                 .setGlobalBatterySaverEnabled(true)
828                 .setBatterySaverEnabled(false)
829                 .build();
830 
831         mService.updateRestrictBackgroundByLowPowerModeUL(stateOnRestrictOff);
832 
833         assertFalse(mService.getRestrictBackground());
834 
835         mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
836 
837         // RestrictBackground should still be off.
838         assertFalse(mService.getRestrictBackground());
839     }
840 
841     @Test
updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()842     public void updateRestrictBackgroundByLowPowerMode_StatusChangedInBsm_DoNotRestore()
843             throws Exception {
844         setRestrictBackground(true);
845         PowerSaveState stateOn = new PowerSaveState.Builder()
846                 .setGlobalBatterySaverEnabled(true)
847                 .setBatterySaverEnabled(true)
848                 .build();
849         mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
850 
851         // RestrictBackground should still be on
852         assertTrue(mService.getRestrictBackground());
853 
854         // User turns off RestrictBackground manually
855         setRestrictBackground(false);
856         // RestrictBackground should be off because user changed it manually
857         assertFalse(mService.getRestrictBackground());
858 
859         PowerSaveState stateOff = new PowerSaveState.Builder()
860                 .setGlobalBatterySaverEnabled(false)
861                 .setBatterySaverEnabled(false)
862                 .build();
863         mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
864 
865         // RestrictBackground should remain off.
866         assertFalse(mService.getRestrictBackground());
867     }
868 
869     @Test
updateRestrictBackgroundByLowPowerMode_RestrictOnWithGlobalOff()870     public void updateRestrictBackgroundByLowPowerMode_RestrictOnWithGlobalOff()
871             throws Exception {
872         setRestrictBackground(false);
873         PowerSaveState stateOn = new PowerSaveState.Builder()
874                 .setGlobalBatterySaverEnabled(false)
875                 .setBatterySaverEnabled(true)
876                 .build();
877 
878         mService.updateRestrictBackgroundByLowPowerModeUL(stateOn);
879 
880         // RestrictBackground should be turned on because of battery saver.
881         assertTrue(mService.getRestrictBackground());
882 
883         PowerSaveState stateRestrictOff = new PowerSaveState.Builder()
884                 .setGlobalBatterySaverEnabled(true)
885                 .setBatterySaverEnabled(false)
886                 .build();
887         mService.updateRestrictBackgroundByLowPowerModeUL(stateRestrictOff);
888 
889         // RestrictBackground should be off, returning to its state before battery saver's change.
890         assertFalse(mService.getRestrictBackground());
891 
892         PowerSaveState stateOff = new PowerSaveState.Builder()
893                 .setGlobalBatterySaverEnabled(false)
894                 .setBatterySaverEnabled(false)
895                 .build();
896         mService.updateRestrictBackgroundByLowPowerModeUL(stateOff);
897 
898         // RestrictBackground should still be off, back in its pre-battery saver state.
899         assertFalse(mService.getRestrictBackground());
900     }
901 
removeRestrictBackgroundAllowlist(boolean expectIntent)902     private void removeRestrictBackgroundAllowlist(boolean expectIntent) throws Exception {
903         assertRestrictBackgroundAllowedUids(UID_A);
904         assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
905 
906         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
907         mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
908 
909         mService.setUidPolicy(UID_A, POLICY_NONE);
910 
911         assertRestrictBackgroundAllowedUids();
912         assertUidPolicy(UID_A, POLICY_NONE);
913         mPolicyListener.waitAndVerify().onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
914         if (expectIntent) {
915             assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
916         } else {
917             futureIntent.assertNotReceived();
918         }
919     }
920 
921     /**
922      * Adds an app to denylist when restrict background is on - app should not receive an intent.
923      */
924     @Test
925     @NetPolicyXml("restrict-background-on.xml")
testAddRestrictBackgroundDenylist_restrictBackgroundOn()926     public void testAddRestrictBackgroundDenylist_restrictBackgroundOn() throws Exception {
927         assertRestrictBackgroundOn();
928         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
929         addRestrictBackgroundDenylist(false);
930     }
931 
932     /**
933      * Adds an app to denylist when restrict background is off - app should receive an intent.
934      */
935     @Test
testAddRestrictBackgroundDenylist_restrictBackgroundOff()936     public void testAddRestrictBackgroundDenylist_restrictBackgroundOff() throws Exception {
937         assertRestrictBackgroundOff();
938         addRestrictBackgroundDenylist(true);
939     }
940 
addRestrictBackgroundDenylist(boolean expectIntent)941     private void addRestrictBackgroundDenylist(boolean expectIntent) throws Exception {
942         assertUidPolicy(UID_A, POLICY_NONE);
943         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
944         mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
945 
946         mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
947 
948         assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
949         mPolicyListener.waitAndVerify()
950                 .onUidPoliciesChanged(APP_ID_A, POLICY_REJECT_METERED_BACKGROUND);
951         if (expectIntent) {
952             assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
953         } else {
954             futureIntent.assertNotReceived();
955         }
956     }
957 
958     /**
959      * Removes an app from denylist when restrict background is on - app should not
960      * receive an intent.
961      */
962     @Test
963     @NetPolicyXml("uidA-denied-restrict-background-on.xml")
testRemoveRestrictBackgroundDenylist_restrictBackgroundOn()964     public void testRemoveRestrictBackgroundDenylist_restrictBackgroundOn() throws Exception {
965         assertRestrictBackgroundOn();
966         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
967         removeRestrictBackgroundDenylist(false);
968     }
969 
970     /**
971      * Removes an app from denylist when restrict background is off - app should
972      * receive an intent.
973      */
974     @Test
975     @NetPolicyXml("uidA-denied-restrict-background-off.xml")
testRemoveRestrictBackgroundDenylist_restrictBackgroundOff()976     public void testRemoveRestrictBackgroundDenylist_restrictBackgroundOff() throws Exception {
977         assertRestrictBackgroundOff();
978         removeRestrictBackgroundDenylist(true);
979     }
980 
removeRestrictBackgroundDenylist(boolean expectIntent)981     private void removeRestrictBackgroundDenylist(boolean expectIntent) throws Exception {
982         assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
983         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
984         mPolicyListener.expect().onUidPoliciesChanged(anyInt(), anyInt());
985 
986         mService.setUidPolicy(UID_A, POLICY_NONE);
987 
988         assertUidPolicy(UID_A, POLICY_NONE);
989         mPolicyListener.waitAndVerify()
990                 .onUidPoliciesChanged(APP_ID_A, POLICY_NONE);
991         if (expectIntent) {
992             assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
993         } else {
994             futureIntent.assertNotReceived();
995         }
996     }
997 
998     @Test
999     @NetPolicyXml("uidA-denied-restrict-background-on.xml")
testDeniedAppIsNotNotifiedWhenRestrictBackgroundIsOn()1000     public void testDeniedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
1001         assertRestrictBackgroundOn();
1002         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
1003         assertUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
1004 
1005         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
1006         setRestrictBackground(true);
1007         futureIntent.assertNotReceived();
1008     }
1009 
1010     @Test
1011     @NetPolicyXml("uidA-allowed-restrict-background-on.xml")
testAllowedAppIsNotNotifiedWhenRestrictBackgroundIsOn()1012     public void testAllowedAppIsNotNotifiedWhenRestrictBackgroundIsOn() throws Exception {
1013         assertRestrictBackgroundOn();
1014         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
1015         assertRestrictBackgroundAllowedUids(UID_A);
1016 
1017         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
1018         setRestrictBackground(true);
1019         futureIntent.assertNotReceived();
1020     }
1021 
1022     @Test
1023     @NetPolicyXml("uidA-allowed-restrict-background-on.xml")
testAllowedAppIsNotifiedWhenDenylisted()1024     public void testAllowedAppIsNotifiedWhenDenylisted() throws Exception {
1025         assertRestrictBackgroundOn();
1026         assertRestrictBackgroundChangedReceived(mFutureIntent, null);
1027         assertRestrictBackgroundAllowedUids(UID_A);
1028 
1029         final FutureIntent futureIntent = newRestrictBackgroundChangedFuture();
1030         mService.setUidPolicy(UID_A, POLICY_REJECT_METERED_BACKGROUND);
1031         assertRestrictBackgroundChangedReceived(futureIntent, PKG_NAME_A);
1032     }
1033 
1034     @Test
1035     @NetPolicyXml("restrict-background-lists-allowlist-format.xml")
testRestrictBackgroundLists_allowlistFormat()1036     public void testRestrictBackgroundLists_allowlistFormat() throws Exception {
1037         restrictBackgroundListsTest();
1038     }
1039 
1040     @Test
1041     @NetPolicyXml("restrict-background-lists-uid-policy-format.xml")
testRestrictBackgroundLists_uidPolicyFormat()1042     public void testRestrictBackgroundLists_uidPolicyFormat() throws Exception {
1043         restrictBackgroundListsTest();
1044     }
1045 
restrictBackgroundListsTest()1046     private void restrictBackgroundListsTest() throws Exception {
1047         // UIds that are in allowlist.
1048         assertRestrictBackgroundAllowedUids(UID_A, UID_B, UID_C);
1049         assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
1050         assertUidPolicy(UID_B, POLICY_ALLOW_METERED_BACKGROUND);
1051         assertUidPolicy(UID_C, POLICY_ALLOW_METERED_BACKGROUND);
1052 
1053         // UIDs that are in denylist.
1054         assertUidPolicy(UID_D, POLICY_NONE);
1055         assertUidPolicy(UID_E, POLICY_REJECT_METERED_BACKGROUND);
1056 
1057         // UIDS that have legacy policies.
1058         assertUidPolicy(UID_F, 2); // POLICY_ALLOW_BACKGROUND_BATTERY_SAVE
1059 
1060         // Remove an uid from allowlist.
1061         mService.setUidPolicy(UID_A, POLICY_NONE);
1062         assertUidPolicy(UID_A, POLICY_NONE);
1063         assertRestrictBackgroundAllowedUids(UID_B, UID_C);
1064 
1065         // Add an app to allowlist which is currently in denylist.
1066         mService.setUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
1067         assertUidPolicy(UID_E, POLICY_ALLOW_METERED_BACKGROUND);
1068         assertRestrictBackgroundAllowedUids(UID_B, UID_C, UID_E);
1069 
1070         // Add an app to denylist when is currently in allowlist.
1071         mService.setUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
1072         assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND);
1073         assertRestrictBackgroundAllowedUids(UID_C, UID_E);
1074     }
1075 
1076     /**
1077      * Tests scenario where an UID had {@code restrict-background} and {@code uid-policy} tags.
1078      */
1079     @Test
1080     @NetPolicyXml("restrict-background-lists-mixed-format.xml")
testRestrictBackgroundLists_mixedFormat()1081     public void testRestrictBackgroundLists_mixedFormat() throws Exception {
1082         assertRestrictBackgroundAllowedUids(UID_A, UID_C, UID_D);
1083         assertUidPolicy(UID_A, POLICY_ALLOW_METERED_BACKGROUND);
1084         assertUidPolicy(UID_B, POLICY_REJECT_METERED_BACKGROUND); // Denylist prevails.
1085         assertUidPolicy(UID_C, (POLICY_ALLOW_METERED_BACKGROUND | 2));
1086         assertUidPolicy(UID_D, POLICY_ALLOW_METERED_BACKGROUND);
1087     }
1088 
1089     @Test
1090     @NetPolicyXml("uids-with-mixed-policies.xml")
testGetUidsWithPolicy()1091     public void testGetUidsWithPolicy() throws Exception {
1092         assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_NONE));
1093         assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_REJECT_METERED_BACKGROUND),
1094                 UID_B, UID_D);
1095         assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND),
1096                 UID_E, UID_F);
1097         // Legacy (POLICY_ALLOW_BACKGROUND_BATTERY_SAVE)
1098         assertContainsInAnyOrder(mService.getUidsWithPolicy(2),
1099                 UID_C, UID_D, UID_F);
1100     }
1101 
1102     // NOTE: testPolicyChangeTriggersListener() is too superficial, they
1103     // don't check for side-effects (like calls to NetworkManagementService) neither cover all
1104     // different modes (Data Saver, Battery Saver, Doze, App idle, etc...).
1105     // These scenarios are extensively tested on CTS' HostsideRestrictBackgroundNetworkTests.
1106     @SuppressWarnings("GuardedBy")
1107     @Test
testUidForeground()1108     public void testUidForeground() throws Exception {
1109         // push all uids into background
1110         long procStateSeq = 0;
1111         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_SERVICE, procStateSeq++);
1112         callAndWaitOnUidStateChanged(UID_B, PROCESS_STATE_SERVICE, procStateSeq++);
1113         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1114         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1115         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1116         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1117 
1118         // push one of the uids into foreground
1119         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_TOP, procStateSeq++);
1120         assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1121         assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1122         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1123         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1124 
1125         // and swap another uid into foreground
1126         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_SERVICE, procStateSeq++);
1127         callAndWaitOnUidStateChanged(UID_B, PROCESS_STATE_TOP, procStateSeq++);
1128         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1129         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1130         assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1131         assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1132 
1133         // change capability of an uid to allow access to power restricted network
1134         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_SERVICE, procStateSeq++,
1135                 PROCESS_CAPABILITY_POWER_RESTRICTED_NETWORK);
1136         callAndWaitOnUidStateChanged(UID_B, PROCESS_STATE_SERVICE, procStateSeq++,
1137                 PROCESS_CAPABILITY_NONE);
1138         assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1139         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1140         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1141         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1142 
1143         // change capability of an uid to allow access to user restricted network
1144         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_IMPORTANT_FOREGROUND, procStateSeq++,
1145                 PROCESS_CAPABILITY_USER_RESTRICTED_NETWORK);
1146         callAndWaitOnUidStateChanged(UID_B, PROCESS_STATE_SERVICE, procStateSeq++,
1147                 PROCESS_CAPABILITY_NONE);
1148         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1149         assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1150         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1151         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1152     }
1153 
1154     @SuppressWarnings("GuardedBy")
1155     @Test
testUidForeground_withPendingState()1156     public void testUidForeground_withPendingState() throws Exception {
1157         long procStateSeq = 0;
1158         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_SERVICE,
1159                 procStateSeq++, PROCESS_CAPABILITY_NONE);
1160         callAndWaitOnUidStateChanged(UID_B, PROCESS_STATE_SERVICE,
1161                 procStateSeq++, PROCESS_CAPABILITY_NONE);
1162         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1163         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1164         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1165         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1166 
1167         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
1168             // Verify that a callback with an old procStateSeq is ignored.
1169             callOnUidStatechanged(UID_A, PROCESS_STATE_TOP, 0,
1170                     PROCESS_CAPABILITY_POWER_RESTRICTED_NETWORK);
1171             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1172             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1173             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1174             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1175 
1176             callOnUidStatechanged(UID_A, PROCESS_STATE_SERVICE, procStateSeq++,
1177                     PROCESS_CAPABILITY_POWER_RESTRICTED_NETWORK);
1178             assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1179             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1180             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1181             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1182 
1183             callOnUidStatechanged(UID_A, PROCESS_STATE_IMPORTANT_FOREGROUND, procStateSeq++,
1184                     PROCESS_CAPABILITY_USER_RESTRICTED_NETWORK);
1185             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1186             assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1187             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1188             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1189 
1190             callOnUidStatechanged(UID_A, PROCESS_STATE_TOP, procStateSeq++,
1191                     PROCESS_CAPABILITY_NONE);
1192             assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1193             assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1194             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1195             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1196         }
1197         waitForUidEventHandlerIdle();
1198 
1199         assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1200         assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1201         assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1202         assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1203 
1204         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
1205             callOnUidStatechanged(UID_A, PROCESS_STATE_SERVICE, procStateSeq++,
1206                     PROCESS_CAPABILITY_NONE);
1207             assertTrue(mService.isUidForegroundOnRestrictPowerUL(UID_A));
1208             assertTrue(mService.isUidForegroundOnRestrictBackgroundUL(UID_A));
1209             assertFalse(mService.isUidForegroundOnRestrictPowerUL(UID_B));
1210             assertFalse(mService.isUidForegroundOnRestrictBackgroundUL(UID_B));
1211         }
1212         waitForUidEventHandlerIdle();
1213     }
1214 
1215     @Test
testAppIdleTempWhitelisting()1216     public void testAppIdleTempWhitelisting() throws Exception {
1217         mService.setAppIdleWhitelist(UID_A, true);
1218         mService.setAppIdleWhitelist(UID_B, false);
1219         int[] whitelistedIds = mService.getAppIdleWhitelist();
1220         assertTrue(Arrays.binarySearch(whitelistedIds, UID_A) >= 0);
1221         assertTrue(Arrays.binarySearch(whitelistedIds, UID_B) < 0);
1222         assertFalse(mService.isUidIdle(UID_A));
1223         // Can't currently guarantee UID_B's app idle state.
1224         // TODO: expand with multiple app idle states.
1225     }
1226 
1227     private static long computeLastCycleBoundary(long currentTime, NetworkPolicy policy) {
1228         RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
1229                 ZoneId.systemDefault());
1230         final Iterator<Range<ZonedDateTime>> it = policy.cycleIterator();
1231         while (it.hasNext()) {
1232             final Range<ZonedDateTime> cycle = it.next();
1233             if (cycle.getLower().toInstant().toEpochMilli() < currentTime) {
1234                 return cycle.getLower().toInstant().toEpochMilli();
1235             }
1236         }
1237         throw new IllegalStateException(
1238                 "Failed to find current cycle for " + policy + " at " + currentTime);
1239     }
1240 
1241     private static long computeNextCycleBoundary(long currentTime, NetworkPolicy policy) {
1242         RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTime),
1243                 ZoneId.systemDefault());
1244         return policy.cycleIterator().next().getUpper().toInstant().toEpochMilli();
1245     }
1246 
1247     @Test
1248     public void testLastCycleBoundaryThisMonth() throws Exception {
1249         // assume cycle day of "5th", which should be in same month
1250         final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
1251         final long expectedCycle = parseTime("2007-11-05T00:00:00.000Z");
1252 
1253         final NetworkPolicy policy = new NetworkPolicy(
1254                 sTemplateWifi, 5, TIMEZONE_UTC, 1024L, 1024L, false);
1255         final long actualCycle = computeLastCycleBoundary(currentTime, policy);
1256         assertTimeEquals(expectedCycle, actualCycle);
1257     }
1258 
1259     @Test
1260     public void testLastCycleBoundaryLastMonth() throws Exception {
1261         // assume cycle day of "20th", which should be in last month
1262         final long currentTime = parseTime("2007-11-14T00:00:00.000Z");
1263         final long expectedCycle = parseTime("2007-10-20T00:00:00.000Z");
1264 
1265         final NetworkPolicy policy = new NetworkPolicy(
1266                 sTemplateWifi, 20, TIMEZONE_UTC, 1024L, 1024L, false);
1267         final long actualCycle = computeLastCycleBoundary(currentTime, policy);
1268         assertTimeEquals(expectedCycle, actualCycle);
1269     }
1270 
1271     @Test
1272     public void testLastCycleBoundaryThisMonthFebruary() throws Exception {
1273         // assume cycle day of "30th" in february; should go to january
1274         final long currentTime = parseTime("2007-02-14T00:00:00.000Z");
1275         final long expectedCycle = parseTime("2007-01-30T00:00:00.000Z");
1276 
1277         final NetworkPolicy policy = new NetworkPolicy(
1278                 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
1279         final long actualCycle = computeLastCycleBoundary(currentTime, policy);
1280         assertTimeEquals(expectedCycle, actualCycle);
1281     }
1282 
1283     @Test
1284     public void testLastCycleBoundaryLastMonthFebruary() throws Exception {
1285         // assume cycle day of "30th" in february, which should clamp
1286         final long currentTime = parseTime("2007-03-14T00:00:00.000Z");
1287         final long expectedCycle = parseTime("2007-02-28T23:59:59.999Z");
1288 
1289         final NetworkPolicy policy = new NetworkPolicy(
1290                 sTemplateWifi, 30, TIMEZONE_UTC, 1024L, 1024L, false);
1291         final long actualCycle = computeLastCycleBoundary(currentTime, policy);
1292         assertTimeEquals(expectedCycle, actualCycle);
1293     }
1294 
1295     @Test
1296     public void testCycleBoundaryLeapYear() throws Exception {
1297         final NetworkPolicy policy = new NetworkPolicy(
1298                 sTemplateWifi, 29, TIMEZONE_UTC, 1024L, 1024L, false);
1299 
1300         assertTimeEquals(parseTime("2012-01-29T00:00:00.000Z"),
1301                 computeNextCycleBoundary(parseTime("2012-01-14T00:00:00.000Z"), policy));
1302         assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
1303                 computeNextCycleBoundary(parseTime("2012-02-14T00:00:00.000Z"), policy));
1304         assertTimeEquals(parseTime("2012-02-29T00:00:00.000Z"),
1305                 computeLastCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
1306         assertTimeEquals(parseTime("2012-03-29T00:00:00.000Z"),
1307                 computeNextCycleBoundary(parseTime("2012-03-14T00:00:00.000Z"), policy));
1308 
1309         assertTimeEquals(parseTime("2007-01-29T00:00:00.000Z"),
1310                 computeNextCycleBoundary(parseTime("2007-01-14T00:00:00.000Z"), policy));
1311         assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
1312                 computeNextCycleBoundary(parseTime("2007-02-14T00:00:00.000Z"), policy));
1313         assertTimeEquals(parseTime("2007-02-28T23:59:59.999Z"),
1314                 computeLastCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
1315         assertTimeEquals(parseTime("2007-03-29T00:00:00.000Z"),
1316                 computeNextCycleBoundary(parseTime("2007-03-14T00:00:00.000Z"), policy));
1317     }
1318 
1319     @Test
1320     public void testNextCycleTimezoneAfterUtc() throws Exception {
1321         // US/Central is UTC-6
1322         final NetworkPolicy policy = new NetworkPolicy(
1323                 sTemplateWifi, 10, "US/Central", 1024L, 1024L, false);
1324         assertTimeEquals(parseTime("2012-01-10T06:00:00.000Z"),
1325                 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
1326     }
1327 
1328     @Test
1329     public void testNextCycleTimezoneBeforeUtc() throws Exception {
1330         // Israel is UTC+2
1331         final NetworkPolicy policy = new NetworkPolicy(
1332                 sTemplateWifi, 10, "Israel", 1024L, 1024L, false);
1333         assertTimeEquals(parseTime("2012-01-09T22:00:00.000Z"),
1334                 computeNextCycleBoundary(parseTime("2012-01-05T00:00:00.000Z"), policy));
1335     }
1336 
1337     @Test
1338     public void testCycleTodayJanuary() throws Exception {
1339         final NetworkPolicy policy = new NetworkPolicy(
1340                 sTemplateWifi, 14, "US/Pacific", 1024L, 1024L, false);
1341 
1342         assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
1343                 computeNextCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
1344         assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
1345                 computeNextCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
1346         assertTimeEquals(parseTime("2013-02-14T00:00:00.000-08:00"),
1347                 computeNextCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
1348 
1349         assertTimeEquals(parseTime("2012-12-14T00:00:00.000-08:00"),
1350                 computeLastCycleBoundary(parseTime("2013-01-13T23:59:59.000-08:00"), policy));
1351         assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
1352                 computeLastCycleBoundary(parseTime("2013-01-14T00:00:01.000-08:00"), policy));
1353         assertTimeEquals(parseTime("2013-01-14T00:00:00.000-08:00"),
1354                 computeLastCycleBoundary(parseTime("2013-01-14T15:11:00.000-08:00"), policy));
1355     }
1356 
1357     @FlakyTest
1358     @Test
1359     public void testNetworkPolicyAppliedCycleLastMonth() throws Exception {
1360         List<NetworkStateSnapshot> snapshots = null;
1361         NetworkStats stats = null;
1362 
1363         final int CYCLE_DAY = 15;
1364         final long NOW = parseTime("2007-03-10T00:00Z");
1365         final long CYCLE_START = parseTime("2007-02-15T00:00Z");
1366         final long CYCLE_END = parseTime("2007-03-15T00:00Z");
1367 
1368         setCurrentTimeMillis(NOW);
1369 
1370         // first, pretend that wifi network comes online. no policy active,
1371         // which means we shouldn't push limit to interface.
1372         snapshots = List.of(buildWifi());
1373         when(mConnManager.getAllNetworkStateSnapshots()).thenReturn(snapshots);
1374 
1375         mPolicyListener.expect().onMeteredIfacesChanged(any());
1376         mServiceContext.sendBroadcast(new Intent(CONNECTIVITY_ACTION));
1377         mPolicyListener.waitAndVerify().onMeteredIfacesChanged(any());
1378 
1379         // now change cycle to be on 15th, and test in early march, to verify we
1380         // pick cycle day in previous month.
1381         when(mConnManager.getAllNetworkStateSnapshots()).thenReturn(snapshots);
1382 
1383         // pretend that 512 bytes total have happened
1384         mDeps.setMockedTotalBytes(UID_A, 256L, 256L);
1385 
1386         mPolicyListener.expect().onMeteredIfacesChanged(any());
1387         setNetworkPolicies(new NetworkPolicy(
1388                 sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, DataUnit.MEBIBYTES.toBytes(1),
1389                 DataUnit.MEBIBYTES.toBytes(2), false));
1390         mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1391 
1392         verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1393                 DataUnit.MEBIBYTES.toBytes(2) - 512);
1394     }
1395 
1396     @Test
1397     public void testNotificationWarningLimitSnooze() throws Exception {
1398         // Get active mobile network in place
1399         expectMobileDefaults();
1400         mService.updateNetworks();
1401 
1402         // Define simple data plan
1403         final SubscriptionPlan plan = buildMonthlyDataPlan(
1404                 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), DataUnit.MEGABYTES.toBytes(1800));
1405         setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
1406                 mServiceContext.getOpPackageName());
1407 
1408         // We're 20% through the month (6 days)
1409         final long start = parseTime("2015-11-01T00:00Z");
1410         final long end = parseTime("2015-11-07T00:00Z");
1411         setCurrentTimeMillis(end);
1412 
1413         // Normal usage means no notification
1414         {
1415             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(360), 0);
1416 
1417             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1418             TelephonyManager tmSub = expectMobileDefaults();
1419             clearInvocations(mNotifManager);
1420 
1421             mService.updateNetworks();
1422 
1423             verify(tmSub, atLeastOnce()).setPolicyDataEnabled(true);
1424             verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1425                     DataUnit.MEGABYTES.toBytes(1800 - 360));
1426             verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1427         }
1428 
1429         // Push over warning
1430         {
1431             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(1799), 0);
1432 
1433             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1434             TelephonyManager tmSub = expectMobileDefaults();
1435             clearInvocations(mNotifManager);
1436 
1437             mService.updateNetworks();
1438 
1439             verify(tmSub, atLeastOnce()).setPolicyDataEnabled(true);
1440             verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1441                     DataUnit.MEGABYTES.toBytes(1800 - 1799));
1442             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_WARNING),
1443                     isA(Notification.class), eq(UserHandle.ALL));
1444         }
1445 
1446         // Push over warning, but with a config that isn't from an identified carrier
1447         {
1448             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(1799), 0);
1449 
1450             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1451             TelephonyManager tmSub = expectMobileDefaults();
1452             expectDefaultCarrierConfig();
1453             clearInvocations(mNotifManager);
1454 
1455             mService.updateNetworks();
1456 
1457             verify(tmSub, atLeastOnce()).setPolicyDataEnabled(true);
1458             verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1459                     DataUnit.MEGABYTES.toBytes(1800 - 1799));
1460             // Since this isn't from the identified carrier, there should be no notifications
1461             verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1462         }
1463 
1464         // Push over limit
1465         {
1466             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(1810), 0);
1467 
1468             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1469             TelephonyManager tmSub = expectMobileDefaults();
1470             clearInvocations(mNotifManager);
1471 
1472             mService.updateNetworks();
1473 
1474             verify(tmSub, atLeastOnce()).setPolicyDataEnabled(false);
1475             verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE, 1);
1476             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT),
1477                     isA(Notification.class), eq(UserHandle.ALL));
1478         }
1479 
1480         // Snooze limit
1481         {
1482             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1483             TelephonyManager tmSub = expectMobileDefaults();
1484             clearInvocations(mNotifManager);
1485 
1486             mService.snoozeLimit(sTemplateCarrierMetered);
1487             mService.updateNetworks();
1488 
1489             verify(tmSub, atLeastOnce()).setPolicyDataEnabled(true);
1490             verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1491                     Long.MAX_VALUE);
1492             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT_SNOOZED),
1493                     isA(Notification.class), eq(UserHandle.ALL));
1494         }
1495         // The sub is no longer used for data(e.g. user uses another sub), hide the notifications.
1496         {
1497             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1498 
1499             notifyDefaultAndActiveDataSubIdChange(TEST_SUB_ID2, TEST_SUB_ID2);
1500             verify(mNotifManager, atLeastOnce()).cancel(any(), eq(TYPE_LIMIT_SNOOZED));
1501         }
1502         // The sub is not active for data(e.g. due to auto data switch), but still default for data,
1503         // show notification.
1504         {
1505             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1506 
1507             notifyDefaultAndActiveDataSubIdChange(TEST_SUB_ID, TEST_SUB_ID2);
1508             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT_SNOOZED),
1509                     isA(Notification.class), eq(UserHandle.ALL));
1510         }
1511         // The sub is active for data, but not the default(e.g. due to auto data switch),
1512         // show notification.
1513         {
1514             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1515 
1516             notifyDefaultAndActiveDataSubIdChange(TEST_SUB_ID2, TEST_SUB_ID);
1517             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_LIMIT_SNOOZED),
1518                     isA(Notification.class), eq(UserHandle.ALL));
1519         }
1520     }
1521 
1522     @Test
1523     public void testNotificationRapid() throws Exception {
1524         // Get active mobile network in place
1525         expectMobileDefaults();
1526         mService.updateNetworks();
1527 
1528         // Define simple data plan which gives us effectively 60MB/day
1529         final SubscriptionPlan plan = buildMonthlyDataPlan(
1530                 ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), DataUnit.MEGABYTES.toBytes(1800));
1531         setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[] { plan },
1532                 mServiceContext.getOpPackageName());
1533 
1534         // We're 20% through the month (6 days)
1535         final long start = parseTime("2015-11-01T00:00Z");
1536         final long end = parseTime("2015-11-07T00:00Z");
1537         setCurrentTimeMillis(end);
1538 
1539         // Using 20% data in 20% time is normal
1540         {
1541             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(360), 0);
1542 
1543             reset(mNotifManager);
1544             mService.updateNetworks();
1545             verify(mNotifManager, never()).notifyAsUser(any(), anyInt(), any(), any());
1546         }
1547 
1548         // Using 80% data in 20% time is alarming; but spread equally among
1549         // three UIDs means we get generic alert
1550         {
1551             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(480), 0);
1552             mDeps.setMockedTotalBytes(UID_B, DataUnit.MEGABYTES.toBytes(480), 0);
1553             mDeps.setMockedTotalBytes(UID_C, DataUnit.MEGABYTES.toBytes(480), 0);
1554 
1555             reset(mNotifManager);
1556             mService.updateNetworks();
1557 
1558             final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
1559             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
1560                     notif.capture(), eq(UserHandle.ALL));
1561 
1562             final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1563                     .toString();
1564             assertFalse(text.contains(PKG_NAME_A));
1565             assertFalse(text.contains(PKG_NAME_B));
1566             assertFalse(text.contains(PKG_NAME_C));
1567         }
1568 
1569         // Using 80% data in 20% time is alarming; but mostly done by one UID
1570         // means we get specific alert
1571         {
1572             mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(960), 0);
1573             mDeps.setMockedTotalBytes(UID_B, DataUnit.MEGABYTES.toBytes(480), 0);
1574             mDeps.setMockedTotalBytes(UID_C, 0, 0);
1575 
1576             reset(mNotifManager);
1577             mService.updateNetworks();
1578 
1579             final ArgumentCaptor<Notification> notif = ArgumentCaptor.forClass(Notification.class);
1580             verify(mNotifManager, atLeastOnce()).notifyAsUser(any(), eq(TYPE_RAPID),
1581                     notif.capture(), eq(UserHandle.ALL));
1582 
1583             final String text = notif.getValue().extras.getCharSequence(Notification.EXTRA_TEXT)
1584                     .toString();
1585             assertTrue(text.contains(PKG_NAME_A));
1586             assertFalse(text.contains(PKG_NAME_B));
1587             assertFalse(text.contains(PKG_NAME_C));
1588         }
1589     }
1590 
1591     @Test
1592     public void testMeteredNetworkWithoutLimit() throws Exception {
1593         List<NetworkStateSnapshot> snapshots = null;
1594         NetworkStats stats = null;
1595 
1596         final long TIME_FEB_15 = 1171497600000L;
1597         final long TIME_MAR_10 = 1173484800000L;
1598         final int CYCLE_DAY = 15;
1599 
1600         setCurrentTimeMillis(TIME_MAR_10);
1601 
1602         // bring up wifi network with metered policy
1603         snapshots = List.of(buildWifi());
1604         mDeps.setMockedTotalBytes(UID_A, 0L, 0L);
1605 
1606         {
1607             when(mConnManager.getAllNetworkStateSnapshots()).thenReturn(snapshots);
1608 
1609             mPolicyListener.expect().onMeteredIfacesChanged(any());
1610             setNetworkPolicies(new NetworkPolicy(
1611                     sTemplateWifi, CYCLE_DAY, TIMEZONE_UTC, WARNING_DISABLED, LIMIT_DISABLED,
1612                     true));
1613             mPolicyListener.waitAndVerify().onMeteredIfacesChanged(eq(new String[]{TEST_IFACE}));
1614 
1615             verify(mNetworkManager, atLeastOnce()).setInterfaceQuota(TEST_IFACE,
1616                     Long.MAX_VALUE);
1617         }
1618     }
1619 
1620     @Test
1621     public void testOnUidStateChanged_notifyAMS() throws Exception {
1622         final long procStateSeq = 222;
1623         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_SERVICE, procStateSeq);
1624         verify(mActivityManagerInternal).notifyNetworkPolicyRulesUpdated(UID_A, procStateSeq);
1625     }
1626 
1627     private void callAndWaitOnUidGone(int uid) throws Exception {
1628         // The disabled argument is used only for ephemeral apps and does not matter here.
1629         mUidObserver.onUidGone(uid, false /* disabled */);
1630         waitForUidEventHandlerIdle();
1631     }
1632 
1633     private void callAndWaitOnUidStateChanged(int uid, int procState, long procStateSeq)
1634             throws Exception {
1635         callAndWaitOnUidStateChanged(uid, procState, procStateSeq,
1636                 PROCESS_CAPABILITY_NONE);
1637     }
1638 
1639     private void callAndWaitOnUidStateChanged(int uid, int procState, long procStateSeq,
1640             int capability) throws Exception {
1641         callOnUidStatechanged(uid, procState, procStateSeq, capability);
1642         waitForUidEventHandlerIdle();
1643     }
1644 
1645     private void callOnUidStatechanged(int uid, int procState, long procStateSeq, int capability)
1646             throws Exception {
1647         mUidObserver.onUidStateChanged(uid, procState, procStateSeq, capability);
1648     }
1649 
1650     private void waitForUidEventHandlerIdle() throws Exception {
1651         final CountDownLatch latch = new CountDownLatch(1);
1652         mService.mUidEventHandler.post(() -> {
1653             latch.countDown();
1654         });
1655         latch.await(2, TimeUnit.SECONDS);
1656     }
1657 
1658     private void assertCycleDayAsExpected(PersistableBundle config, int carrierCycleDay,
1659             boolean expectValid) {
1660         config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, carrierCycleDay);
1661         int actualCycleDay = mService.getCycleDayFromCarrierConfig(config,
1662                 INVALID_CARRIER_CONFIG_VALUE);
1663         if (expectValid) {
1664             assertEquals(carrierCycleDay, actualCycleDay);
1665         } else {
1666             // INVALID_CARRIER_CONFIG_VALUE is returned for invalid values
1667             assertEquals(INVALID_CARRIER_CONFIG_VALUE, actualCycleDay);
1668         }
1669     }
1670 
1671     @Test
1672     public void testGetCycleDayFromCarrierConfig() {
1673         PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1674         final Calendar cal = Calendar.getInstance();
1675         int actualCycleDay;
1676 
1677         config.putInt(KEY_MONTHLY_DATA_CYCLE_DAY_INT, DATA_CYCLE_USE_PLATFORM_DEFAULT);
1678         actualCycleDay = mService.getCycleDayFromCarrierConfig(config, DEFAULT_CYCLE_DAY);
1679         assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1680 
1681         // null config returns a default value
1682         actualCycleDay = mService.getCycleDayFromCarrierConfig(null, DEFAULT_CYCLE_DAY);
1683         assertEquals(DEFAULT_CYCLE_DAY, actualCycleDay);
1684 
1685         // Valid, non-default values
1686         assertCycleDayAsExpected(config, 1, true);
1687         assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH), true);
1688         assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH), true);
1689 
1690         // Invalid values
1691         assertCycleDayAsExpected(config, 0, false);
1692         assertCycleDayAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, false);
1693         assertCycleDayAsExpected(config, cal.getMaximum(Calendar.DAY_OF_MONTH) + 1, false);
1694         assertCycleDayAsExpected(config, cal.getMinimum(Calendar.DAY_OF_MONTH) - 5, false);
1695     }
1696 
1697     private void assertWarningBytesAsExpected(PersistableBundle config, long carrierWarningBytes,
1698             long expected) {
1699         config.putLong(KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1700         long actualWarning = mService.getWarningBytesFromCarrierConfig(config,
1701                 INVALID_CARRIER_CONFIG_VALUE);
1702         assertEquals(expected, actualWarning);
1703     }
1704 
1705     @Test
1706     public void testGetWarningBytesFromCarrierConfig() {
1707         PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1708         long actualWarningBytes;
1709 
1710         assertWarningBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1711                 mDefaultWarningBytes);
1712         assertWarningBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, WARNING_DISABLED);
1713         assertWarningBytesAsExpected(config, 0, 0);
1714         // not a valid value
1715         assertWarningBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1716 
1717         // null config returns a default value
1718         actualWarningBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultWarningBytes);
1719         assertEquals(mDefaultWarningBytes, actualWarningBytes);
1720     }
1721 
1722     private void assertLimitBytesAsExpected(PersistableBundle config,  long carrierWarningBytes,
1723             long expected) {
1724         config.putLong(KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, carrierWarningBytes);
1725         long actualWarning = mService.getLimitBytesFromCarrierConfig(config,
1726                 INVALID_CARRIER_CONFIG_VALUE);
1727         assertEquals(expected, actualWarning);
1728     }
1729 
1730     @Test
1731     public void testGetLimitBytesFromCarrierConfig() {
1732         PersistableBundle config = CarrierConfigManager.getDefaultConfig();
1733         long actualLimitBytes;
1734 
1735         assertLimitBytesAsExpected(config, DATA_CYCLE_USE_PLATFORM_DEFAULT,
1736                 mDefaultLimitBytes);
1737         assertLimitBytesAsExpected(config, DATA_CYCLE_THRESHOLD_DISABLED, LIMIT_DISABLED);
1738         assertLimitBytesAsExpected(config, 0, 0);
1739         // not a valid value
1740         assertLimitBytesAsExpected(config, -1000, INVALID_CARRIER_CONFIG_VALUE);
1741 
1742         // null config returns a default value
1743         actualLimitBytes = mService.getWarningBytesFromCarrierConfig(null, mDefaultLimitBytes);
1744         assertEquals(mDefaultLimitBytes, actualLimitBytes);
1745     }
1746 
1747     private PersistableBundle setupUpdateCarrierPolicyCycleTests() throws RemoteException {
1748         when(mConnManager.getAllNetworkStateSnapshots())
1749                 .thenReturn(new ArrayList<NetworkStateSnapshot>());
1750 
1751         setupTelephonySubscriptionManagers(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1752 
1753         PersistableBundle bundle = CarrierConfigManager.getDefaultConfig();
1754         when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(bundle);
1755         setNetworkPolicies(buildDefaultFakeCarrierPolicy());
1756         return bundle;
1757     }
1758 
1759     @Test
1760     public void testUpdateCarrierPolicyCycleWithNullConfig() throws RemoteException {
1761         when(mConnManager.getAllNetworkStateSnapshots())
1762                 .thenReturn(new ArrayList<NetworkStateSnapshot>());
1763 
1764         setupTelephonySubscriptionManagers(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
1765 
1766         when(mCarrierConfigManager.getConfigForSubId(FAKE_SUB_ID)).thenReturn(null);
1767         setNetworkPolicies(buildDefaultFakeCarrierPolicy());
1768         // smoke test to make sure no errors are raised
1769         mServiceContext.sendBroadcast(
1770                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1771                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1772         );
1773         assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1774                 true);
1775     }
1776 
1777     @Test
1778     public void testUpdateCarrierPolicyCycleWithInvalidConfig() throws RemoteException {
1779         PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests();
1780         // Test with an invalid CarrierConfig, there should be no changes or crashes.
1781         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, -100);
1782         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, -100);
1783         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, -100);
1784         mServiceContext.sendBroadcast(
1785                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1786                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1787         );
1788 
1789         assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1790                 true);
1791     }
1792 
1793     @Test
1794     public void testUpdateCarrierPolicyCycleWithDefaultConfig() throws RemoteException {
1795         PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests();
1796         // Test that we respect the platform values when told to
1797         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1798                 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1799         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1800                 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1801         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1802                 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1803         mServiceContext.sendBroadcast(
1804                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1805                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1806         );
1807 
1808         assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1809                 true);
1810     }
1811 
1812     @Test
1813     public void testUpdateCarrierPolicyCycleWithUserOverrides() throws RemoteException {
1814         PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests();
1815 
1816         // inferred = false implies that a user manually modified this policy.
1817         NetworkPolicy policy = buildDefaultFakeCarrierPolicy();
1818         policy.inferred = false;
1819         setNetworkPolicies(policy);
1820 
1821         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1822         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1823         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1824                 DATA_CYCLE_THRESHOLD_DISABLED);
1825         mServiceContext.sendBroadcast(
1826                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1827                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1828         );
1829 
1830         // The policy still shouldn't change, because we don't want to overwrite user settings.
1831         assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
1832                 false);
1833     }
1834 
1835     @Test
1836     public void testUpdateCarrierPolicyCycleUpdatesDataCycle() throws RemoteException {
1837         PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests();
1838 
1839         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1840         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG, 9999);
1841         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG, 9999);
1842         mServiceContext.sendBroadcast(
1843                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1844                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1845         );
1846 
1847         assertNetworkPolicyEquals(31, 9999, 9999, true);
1848     }
1849 
1850     @Test
1851     public void testUpdateCarrierPolicyCycleDisableThresholds() throws RemoteException {
1852         PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests();
1853 
1854         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1855         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1856                 DATA_CYCLE_THRESHOLD_DISABLED);
1857         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1858                 DATA_CYCLE_THRESHOLD_DISABLED);
1859         mServiceContext.sendBroadcast(
1860                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1861                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1862         );
1863 
1864         assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1865     }
1866 
1867     @Test
1868     public void testUpdateCarrierPolicyCycleRevertsToDefault() throws RemoteException {
1869         PersistableBundle bundle = setupUpdateCarrierPolicyCycleTests();
1870 
1871         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT, 31);
1872         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1873                 DATA_CYCLE_THRESHOLD_DISABLED);
1874         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1875                 DATA_CYCLE_THRESHOLD_DISABLED);
1876         mServiceContext.sendBroadcast(
1877                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1878                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1879         );
1880         assertNetworkPolicyEquals(31, WARNING_DISABLED, LIMIT_DISABLED, true);
1881 
1882         // If the user switches carriers to one that doesn't use a CarrierConfig, we should revert
1883         // to the default data limit and warning. The cycle date doesn't need to revert as it's
1884         // arbitrary anyways.
1885         bundle.putInt(CarrierConfigManager.KEY_MONTHLY_DATA_CYCLE_DAY_INT,
1886                 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1887         bundle.putLong(CarrierConfigManager.KEY_DATA_WARNING_THRESHOLD_BYTES_LONG,
1888                 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1889         bundle.putLong(CarrierConfigManager.KEY_DATA_LIMIT_THRESHOLD_BYTES_LONG,
1890                 DATA_CYCLE_USE_PLATFORM_DEFAULT);
1891         mServiceContext.sendBroadcast(
1892                 new Intent(ACTION_CARRIER_CONFIG_CHANGED)
1893                         .putExtra(CarrierConfigManager.EXTRA_SUBSCRIPTION_INDEX, FAKE_SUB_ID)
1894         );
1895 
1896         assertNetworkPolicyEquals(31, mDefaultWarningBytes, mDefaultLimitBytes,
1897                 true);
1898     }
1899 
1900     @Test
1901     public void testOpportunisticQuota() throws Exception {
1902         final Network net = TEST_NETWORK;
1903         final NetworkPolicyManagerInternal internal = LocalServices
1904                 .getService(NetworkPolicyManagerInternal.class);
1905 
1906         // Get active mobile network in place
1907         expectMobileDefaults();
1908         mService.updateNetworks();
1909 
1910         // We're 20% through the month (6 days)
1911         final long start = parseTime("2015-11-01T00:00Z");
1912         final long end = parseTime("2015-11-07T00:00Z");
1913         setCurrentTimeMillis(end);
1914 
1915         // Get some data usage in place
1916         mDeps.setMockedTotalBytes(UID_A, DataUnit.MEGABYTES.toBytes(360), 0);
1917 
1918         // No data plan
1919         {
1920             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1921             expectMobileDefaults();
1922 
1923             mService.updateNetworks();
1924 
1925             // No quotas
1926             assertEquals(OPPORTUNISTIC_QUOTA_UNKNOWN,
1927                     internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1928             assertEquals(OPPORTUNISTIC_QUOTA_UNKNOWN,
1929                     internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1930         }
1931 
1932         // Limited data plan
1933         {
1934             final SubscriptionPlan plan = buildMonthlyDataPlan(
1935                     ZonedDateTime.parse("2015-11-01T00:00:00.00Z"),
1936                     DataUnit.MEGABYTES.toBytes(1800));
1937             setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
1938                     mServiceContext.getOpPackageName());
1939 
1940             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1941             expectMobileDefaults();
1942 
1943             mService.updateNetworks();
1944 
1945             // We have 1440MB and 24 days left, which is 60MB/day; assuming 10%
1946             // for quota split equally between two types gives 3MB.
1947             assertEquals(DataUnit.MEGABYTES.toBytes(3),
1948                     internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1949             assertEquals(DataUnit.MEGABYTES.toBytes(3),
1950                     internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1951         }
1952 
1953         // Limited data plan, over quota
1954         {
1955             final SubscriptionPlan plan = buildMonthlyDataPlan(
1956                     ZonedDateTime.parse("2015-11-01T00:00:00.00Z"),
1957                     DataUnit.MEGABYTES.toBytes(100));
1958             setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
1959                     mServiceContext.getOpPackageName());
1960 
1961             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1962             expectMobileDefaults();
1963 
1964             mService.updateNetworks();
1965 
1966             assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1967             assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1968         }
1969 
1970         // Roaming
1971         {
1972             final SubscriptionPlan plan = buildMonthlyDataPlan(
1973                     ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), BYTES_UNLIMITED);
1974             setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
1975                     mServiceContext.getOpPackageName());
1976 
1977             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1978             expectMobileDefaults();
1979             expectNetworkStateSnapshot(true /* roaming */);
1980 
1981             mService.updateNetworks();
1982 
1983             assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
1984             assertEquals(0L, internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
1985         }
1986 
1987         // Unlimited data plan
1988         {
1989             final SubscriptionPlan plan = buildMonthlyDataPlan(
1990                     ZonedDateTime.parse("2015-11-01T00:00:00.00Z"), BYTES_UNLIMITED);
1991             setSubscriptionPlans(TEST_SUB_ID, new SubscriptionPlan[]{plan},
1992                     mServiceContext.getOpPackageName());
1993 
1994             reset(mTelephonyManager, mNetworkManager, mNotifManager);
1995             expectMobileDefaults();
1996 
1997             mService.updateNetworks();
1998 
1999             // 20MB/day, split equally between two types gives 10MB.
2000             assertEquals(DataUnit.MEBIBYTES.toBytes(10),
2001                     internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_JOBS));
2002             assertEquals(DataUnit.MEBIBYTES.toBytes(10),
2003                     internal.getSubscriptionOpportunisticQuota(net, QUOTA_TYPE_MULTIPATH));
2004 
2005             // Capabilities change to roaming
2006             final ConnectivityManager.NetworkCallback callback = mNetworkCallbackCaptor.getValue();
2007             assertNotNull(callback);
2008             expectNetworkStateSnapshot(true /* roaming */);
2009             callback.onCapabilitiesChanged(
2010                     TEST_NETWORK, buildNetworkCapabilities(TEST_SUB_ID, true /* roaming */));
2011 
2012             assertEquals(0, internal.getSubscriptionOpportunisticQuota(
2013                     TEST_NETWORK, NetworkPolicyManagerInternal.QUOTA_TYPE_MULTIPATH));
2014         }
2015     }
2016 
2017     /**
2018      * Test that policy set of {null, NetworkPolicy, null} does not crash and restores the valid
2019      * NetworkPolicy.
2020      */
2021     @Test
2022     public void testSetNetworkPolicies_withNullPolicies_doesNotThrow() {
2023         NetworkPolicy[] policies = new NetworkPolicy[3];
2024         policies[1] = buildDefaultFakeCarrierPolicy();
2025         setNetworkPolicies(policies);
2026 
2027         assertNetworkPolicyEquals(DEFAULT_CYCLE_DAY, mDefaultWarningBytes, mDefaultLimitBytes,
2028                 true);
2029     }
2030 
2031     private void triggerOnStatsProviderWarningOrLimitReached() throws InterruptedException {
2032         mService.notifyStatsProviderWarningOrLimitReached();
2033         // Wait for processing of MSG_STATS_PROVIDER_WARNING_OR_LIMIT_REACHED.
2034         postMsgAndWaitForCompletion();
2035         verify(mStatsManager).forceUpdate();
2036         // Wait for processing of MSG_*_INTERFACE_QUOTAS.
2037         postMsgAndWaitForCompletion();
2038     }
2039 
2040     /**
2041      * Test that when StatsProvider triggers warning and limit reached, new quotas will be
2042      * calculated and re-armed.
2043      */
2044     @Test
2045     public void testStatsProviderWarningAndLimitReached() throws Exception {
2046         final int CYCLE_DAY = 15;
2047 
2048         mDeps.setMockedTotalBytes(UID_A, 2999, 2000);
2049 
2050         // Get active mobile network in place
2051         expectMobileDefaults();
2052         mService.updateNetworks();
2053         verify(mStatsManager).setStatsProviderWarningAndLimitAsync(TEST_IFACE, Long.MAX_VALUE,
2054                 Long.MAX_VALUE);
2055 
2056         // Set warning to 7KB and limit to 10KB.
2057         setNetworkPolicies(new NetworkPolicy(
2058                 sTemplateCarrierMetered, CYCLE_DAY, TIMEZONE_UTC, 7000L, 10000L,
2059                 true));
2060         postMsgAndWaitForCompletion();
2061 
2062         // Verifies that remaining quotas are set to providers.
2063         verify(mStatsManager).setStatsProviderWarningAndLimitAsync(TEST_IFACE, 2001L, 5001L);
2064         reset(mStatsManager);
2065 
2066         // Increase the usage and simulates that limit reached fires earlier by provider,
2067         // but actually the quota is not yet reached. Verifies that the limit reached leads to
2068         // a force update and new quotas should be set.
2069         mDeps.increaseMockedTotalBytes(UID_A, 1000, 999);
2070         triggerOnStatsProviderWarningOrLimitReached();
2071         verify(mStatsManager).setStatsProviderWarningAndLimitAsync(TEST_IFACE, 2L, 3002L);
2072         reset(mStatsManager);
2073 
2074         // Increase the usage and simulate warning reached, the new warning should be unlimited
2075         // since service will disable warning quota to stop lower layer from keep triggering
2076         // warning reached event.
2077         mDeps.increaseMockedTotalBytes(UID_A, 1000L, 1000);
2078         triggerOnStatsProviderWarningOrLimitReached();
2079         verify(mStatsManager).setStatsProviderWarningAndLimitAsync(
2080                 TEST_IFACE, Long.MAX_VALUE, 1002L);
2081         reset(mStatsManager);
2082 
2083         // Increase the usage that over the warning and limit, the new limit should set to 1 to
2084         // block the network traffic.
2085         mDeps.increaseMockedTotalBytes(UID_A, 1000L, 1000);
2086         triggerOnStatsProviderWarningOrLimitReached();
2087         verify(mStatsManager).setStatsProviderWarningAndLimitAsync(TEST_IFACE, Long.MAX_VALUE, 1L);
2088         reset(mStatsManager);
2089     }
2090 
2091     private void enableRestrictedMode(boolean enable) throws Exception {
2092         mService.mRestrictedNetworkingMode = enable;
2093         mService.updateRestrictedModeAllowlistUL();
2094         verify(mNetworkManager).setFirewallChainEnabled(FIREWALL_CHAIN_RESTRICTED,
2095                 enable);
2096     }
2097 
2098     @Test
2099     public void testUpdateRestrictedModeAllowlist() throws Exception {
2100         // initialization calls setFirewallChainEnabled, so we want to reset the invocations.
2101         clearInvocations(mNetworkManager);
2102         expectHasUseRestrictedNetworksPermission(UID_A, true);
2103         expectHasUseRestrictedNetworksPermission(UID_B, false);
2104 
2105         // Set low enough proc-states to ensure these uids are allowed in the background chain.
2106         // To maintain clean separation between separate firewall chains, the tests could
2107         // check for the specific blockedReasons in the uidBlockedState.
2108         callAndWaitOnUidStateChanged(UID_A, BACKGROUND_THRESHOLD_STATE - 1, 21);
2109         callAndWaitOnUidStateChanged(UID_B, BACKGROUND_THRESHOLD_STATE - 1, 21);
2110 
2111         Map<Integer, Integer> firewallUidRules = new ArrayMap<>();
2112         doAnswer(arg -> {
2113             int[] uids = arg.getArgument(1);
2114             int[] rules = arg.getArgument(2);
2115             assertTrue(uids.length == rules.length);
2116 
2117             for (int i = 0; i < uids.length; ++i) {
2118                 firewallUidRules.put(uids[i], rules[i]);
2119             }
2120             return null;
2121         }).when(mNetworkManager).setFirewallUidRules(eq(FIREWALL_CHAIN_RESTRICTED),
2122                 any(int[].class), any(int[].class));
2123 
2124         enableRestrictedMode(true);
2125         assertEquals(FIREWALL_RULE_ALLOW, firewallUidRules.get(UID_A).intValue());
2126         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2127         assertTrue(mService.isUidNetworkingBlocked(UID_B, false));
2128 
2129         enableRestrictedMode(false);
2130         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2131         assertFalse(mService.isUidNetworkingBlocked(UID_B, false));
2132     }
2133 
2134     @Test
testUpdateRestrictedModeForUid()2135     public void testUpdateRestrictedModeForUid() throws Exception {
2136         // initialization calls setFirewallChainEnabled, so we want to reset the invocations.
2137         clearInvocations(mNetworkManager);
2138         expectHasUseRestrictedNetworksPermission(UID_A, true);
2139         expectHasUseRestrictedNetworksPermission(UID_B, false);
2140         enableRestrictedMode(true);
2141 
2142         // UID_D and UID_E are not part of installed applications list, so it won't have any
2143         // firewall rules set yet
2144         expectHasUseRestrictedNetworksPermission(UID_D, false);
2145         mService.updateRestrictedModeForUidUL(UID_D);
2146         verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_RESTRICTED, UID_D,
2147                 FIREWALL_RULE_DEFAULT);
2148         assertTrue(mService.isUidNetworkingBlocked(UID_D, false));
2149 
2150         expectHasUseRestrictedNetworksPermission(UID_E, true);
2151         mService.updateRestrictedModeForUidUL(UID_E);
2152         verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_RESTRICTED, UID_E,
2153                 FIREWALL_RULE_ALLOW);
2154         assertFalse(mService.isUidNetworkingBlocked(UID_E, false));
2155     }
2156 
2157     @Test
2158     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testBackgroundChainEnabled()2159     public void testBackgroundChainEnabled() throws Exception {
2160         verify(mNetworkManager).setFirewallChainEnabled(FIREWALL_CHAIN_BACKGROUND, true);
2161     }
2162 
2163     @Test
2164     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
2165     @RequiresFlagsDisabled(Flags.FLAG_USE_DIFFERENT_DELAYS_FOR_BACKGROUND_CHAIN)
testBackgroundChainOnProcStateChangeSameDelay()2166     public void testBackgroundChainOnProcStateChangeSameDelay() throws Exception {
2167         // initialization calls setFirewallChainEnabled, so we want to reset the invocations.
2168         clearInvocations(mNetworkManager);
2169 
2170         mService.mBackgroundRestrictionDelayMs = 500; // To avoid waiting too long in tests.
2171 
2172         // The app will be blocked when there is no prior proc-state.
2173         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2174 
2175         int procStateSeq = 23;
2176         callAndWaitOnUidStateChanged(UID_A, BACKGROUND_THRESHOLD_STATE - 1, procStateSeq++);
2177 
2178         verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2179                 FIREWALL_RULE_ALLOW);
2180         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2181 
2182         callAndWaitOnUidStateChanged(UID_A, BACKGROUND_THRESHOLD_STATE + 1, procStateSeq++);
2183 
2184         // The app should be blocked after a delay. Posting a message just after the delay and
2185         // waiting for it to complete to ensure that the blocking code has executed.
2186         waitForDelayedMessageOnHandler(mService.mBackgroundRestrictionDelayMs + 1);
2187 
2188         verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2189                 FIREWALL_RULE_DEFAULT);
2190         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2191     }
2192 
2193     @Test
2194     @RequiresFlagsEnabled({
2195             Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE,
2196             Flags.FLAG_USE_DIFFERENT_DELAYS_FOR_BACKGROUND_CHAIN
2197     })
testBackgroundChainOnProcStateChangeDifferentDelays()2198     public void testBackgroundChainOnProcStateChangeDifferentDelays() throws Exception {
2199         // The app will be blocked when there is no prior proc-state.
2200         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2201 
2202         // Tweak delays to avoid waiting too long in tests.
2203         mService.mBackgroundRestrictionShortDelayMs = 50;
2204         mService.mBackgroundRestrictionLongDelayMs = 1000;
2205 
2206         int procStateSeq = 231; // Any arbitrary starting sequence.
2207         for (int ps = BACKGROUND_THRESHOLD_STATE; ps <= MAX_PROCESS_STATE; ps++) {
2208             clearInvocations(mNetworkManager);
2209 
2210             // Make sure app is in correct process-state to access network.
2211             callAndWaitOnUidStateChanged(UID_A, BACKGROUND_THRESHOLD_STATE - 1, procStateSeq++);
2212             verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2213                     FIREWALL_RULE_ALLOW);
2214             assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2215 
2216             // Now put the app into the background and test that it eventually loses network.
2217             callAndWaitOnUidStateChanged(UID_A, ps, procStateSeq++);
2218 
2219             final long uidStateChangeTime = SystemClock.uptimeMillis();
2220             if (ps <= PROCESS_STATE_LAST_ACTIVITY) {
2221                 // Verify that the app is blocked after long delay but not after short delay.
2222                 waitForDelayedMessageOnHandler(mService.mBackgroundRestrictionShortDelayMs + 1);
2223                 verify(mNetworkManager, never()).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND,
2224                         UID_A, FIREWALL_RULE_DEFAULT);
2225                 assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2226 
2227                 final long timeUntilLongDelay = uidStateChangeTime
2228                         + mService.mBackgroundRestrictionLongDelayMs - SystemClock.uptimeMillis();
2229                 assertTrue("No time left to verify long delay in background transition",
2230                         timeUntilLongDelay >= 0);
2231 
2232                 waitForDelayedMessageOnHandler(timeUntilLongDelay + 1);
2233                 verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2234                         FIREWALL_RULE_DEFAULT);
2235                 assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2236             } else {
2237                 // Verify that the app is blocked after short delay.
2238                 waitForDelayedMessageOnHandler(mService.mBackgroundRestrictionShortDelayMs + 1);
2239                 verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2240                         FIREWALL_RULE_DEFAULT);
2241                 assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2242             }
2243         }
2244     }
2245 
2246     @Test
2247     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testBackgroundChainOnAllowlistChange()2248     public void testBackgroundChainOnAllowlistChange() throws Exception {
2249         // initialization calls setFirewallChainEnabled, so we want to reset the invocations.
2250         clearInvocations(mNetworkManager);
2251 
2252         // The apps will be blocked when there is no prior proc-state.
2253         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2254         assertTrue(mService.isUidNetworkingBlocked(UID_B, false));
2255 
2256         final int procStateSeq = 29;
2257         callAndWaitOnUidStateChanged(UID_A, BACKGROUND_THRESHOLD_STATE + 1, procStateSeq);
2258         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2259 
2260         when(mPowerExemptionManager.getAllowListedAppIds(anyBoolean()))
2261                 .thenReturn(new int[]{APP_ID_A, APP_ID_B});
2262         final SparseIntArray firewallUidRules = new SparseIntArray();
2263         doAnswer(arg -> {
2264             final int[] uids = arg.getArgument(1);
2265             final int[] rules = arg.getArgument(2);
2266             assertTrue(uids.length == rules.length);
2267 
2268             for (int i = 0; i < uids.length; ++i) {
2269                 firewallUidRules.put(uids[i], rules[i]);
2270             }
2271             return null;
2272         }).when(mNetworkManager).setFirewallUidRules(eq(FIREWALL_CHAIN_BACKGROUND),
2273                 any(int[].class), any(int[].class));
2274 
2275         mPowerAllowlistReceiver.onReceive(mServiceContext, null);
2276 
2277         assertEquals(FIREWALL_RULE_ALLOW, firewallUidRules.get(UID_A, -1));
2278         assertEquals(FIREWALL_RULE_ALLOW, firewallUidRules.get(UID_B, -1));
2279 
2280         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2281         assertFalse(mService.isUidNetworkingBlocked(UID_B, false));
2282     }
2283 
2284     @Test
2285     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testBackgroundChainOnTempAllowlistChange()2286     public void testBackgroundChainOnTempAllowlistChange() throws Exception {
2287         // initialization calls setFirewallChainEnabled, so we want to reset the invocations.
2288         clearInvocations(mNetworkManager);
2289 
2290         // The app will be blocked as is no prior proc-state.
2291         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2292 
2293         final int procStateSeq = 19;
2294         callAndWaitOnUidStateChanged(UID_A, BACKGROUND_THRESHOLD_STATE + 1, procStateSeq);
2295         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2296 
2297         final NetworkPolicyManagerInternal internal = LocalServices.getService(
2298                 NetworkPolicyManagerInternal.class);
2299 
2300         internal.onTempPowerSaveWhitelistChange(APP_ID_A, true, REASON_OTHER, "testing");
2301 
2302         verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2303                 FIREWALL_RULE_ALLOW);
2304         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2305 
2306         internal.onTempPowerSaveWhitelistChange(APP_ID_A, false, REASON_OTHER, "testing");
2307 
2308         verify(mNetworkManager).setFirewallUidRule(FIREWALL_CHAIN_BACKGROUND, UID_A,
2309                 FIREWALL_RULE_DEFAULT);
2310         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2311     }
2312 
isUidState(int uid, int procState, int procStateSeq, int capability)2313     private boolean isUidState(int uid, int procState, int procStateSeq, int capability) {
2314         final NetworkPolicyManager.UidState uidState = mService.getUidStateForTest(uid);
2315         if (uidState == null) {
2316             return false;
2317         }
2318         return uidState.uid == uid && uidState.procStateSeq == procStateSeq
2319                 && uidState.procState == procState && uidState.capability == capability;
2320     }
2321 
2322     @Test
2323     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testUidObserverFiltersProcStateChanges()2324     public void testUidObserverFiltersProcStateChanges() throws Exception {
2325         int testProcStateSeq = 0;
2326         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2327             // First callback for uid.
2328             callOnUidStatechanged(UID_A, BACKGROUND_THRESHOLD_STATE + 1, testProcStateSeq++,
2329                     PROCESS_CAPABILITY_NONE);
2330             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2331         }
2332         waitForUidEventHandlerIdle();
2333         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2334             // Doesn't cross the background threshold.
2335             callOnUidStatechanged(UID_A, BACKGROUND_THRESHOLD_STATE, testProcStateSeq++,
2336                     PROCESS_CAPABILITY_NONE);
2337             assertFalse(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2338         }
2339         waitForUidEventHandlerIdle();
2340         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2341             // Crosses the background threshold.
2342             callOnUidStatechanged(UID_A, BACKGROUND_THRESHOLD_STATE - 1, testProcStateSeq++,
2343                     PROCESS_CAPABILITY_NONE);
2344             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2345         }
2346         waitForUidEventHandlerIdle();
2347         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2348             // Doesn't cross the foreground threshold.
2349             callOnUidStatechanged(UID_A, FOREGROUND_THRESHOLD_STATE + 1, testProcStateSeq++,
2350                     PROCESS_CAPABILITY_NONE);
2351             assertFalse(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2352         }
2353         waitForUidEventHandlerIdle();
2354         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2355             // Crosses the foreground threshold.
2356             callOnUidStatechanged(UID_A, FOREGROUND_THRESHOLD_STATE, testProcStateSeq++,
2357                     PROCESS_CAPABILITY_NONE);
2358             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2359         }
2360         waitForUidEventHandlerIdle();
2361         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2362             // Doesn't cross the top threshold.
2363             callOnUidStatechanged(UID_A, TOP_THRESHOLD_STATE + 1, testProcStateSeq++,
2364                     PROCESS_CAPABILITY_NONE);
2365             assertFalse(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2366         }
2367         waitForUidEventHandlerIdle();
2368         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2369             // Crosses the top threshold.
2370             callOnUidStatechanged(UID_A, TOP_THRESHOLD_STATE, testProcStateSeq++,
2371                     PROCESS_CAPABILITY_NONE);
2372             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2373         }
2374         waitForUidEventHandlerIdle();
2375         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2376             // Doesn't cross any threshold, but changes below TOP_THRESHOLD_STATE should always
2377             // be processed
2378             callOnUidStatechanged(UID_A, TOP_THRESHOLD_STATE - 1, testProcStateSeq++,
2379                     PROCESS_CAPABILITY_NONE);
2380             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2381         }
2382         waitForUidEventHandlerIdle();
2383     }
2384 
2385     @Test
2386     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testUidObserverFiltersStaleChanges()2387     public void testUidObserverFiltersStaleChanges() throws Exception {
2388         final int testProcStateSeq = 51;
2389         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2390             // First callback for uid.
2391             callOnUidStatechanged(UID_B, BACKGROUND_THRESHOLD_STATE + 100, testProcStateSeq,
2392                     PROCESS_CAPABILITY_NONE);
2393             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2394         }
2395         waitForUidEventHandlerIdle();
2396         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2397             // Stale callback because the procStateSeq is smaller.
2398             callOnUidStatechanged(UID_B, BACKGROUND_THRESHOLD_STATE - 100, testProcStateSeq - 10,
2399                     PROCESS_CAPABILITY_NONE);
2400             assertFalse(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2401         }
2402         waitForUidEventHandlerIdle();
2403     }
2404 
2405     @Test
2406     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testUidObserverFiltersCapabilityChanges()2407     public void testUidObserverFiltersCapabilityChanges() throws Exception {
2408         int testProcStateSeq = 0;
2409         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2410             // First callback for uid.
2411             callOnUidStatechanged(UID_A, FOREGROUND_THRESHOLD_STATE, testProcStateSeq++,
2412                     PROCESS_CAPABILITY_NONE);
2413             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2414         }
2415         waitForUidEventHandlerIdle();
2416         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2417             // The same process-state with one network capability added.
2418             callOnUidStatechanged(UID_A, FOREGROUND_THRESHOLD_STATE, testProcStateSeq++,
2419                     PROCESS_CAPABILITY_USER_RESTRICTED_NETWORK);
2420             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2421         }
2422         waitForUidEventHandlerIdle();
2423         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2424             // The same process-state with another network capability added.
2425             callOnUidStatechanged(UID_A, FOREGROUND_THRESHOLD_STATE, testProcStateSeq++,
2426                     PROCESS_CAPABILITY_POWER_RESTRICTED_NETWORK
2427                             | PROCESS_CAPABILITY_USER_RESTRICTED_NETWORK);
2428             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2429         }
2430         waitForUidEventHandlerIdle();
2431         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2432             // The same process-state with all capabilities, but no change in network capabilities.
2433             callOnUidStatechanged(UID_A, FOREGROUND_THRESHOLD_STATE, testProcStateSeq++,
2434                     PROCESS_CAPABILITY_ALL);
2435             assertFalse(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2436         }
2437         waitForUidEventHandlerIdle();
2438 
2439         callAndWaitOnUidStateChanged(UID_A, TOP_THRESHOLD_STATE, testProcStateSeq++,
2440                 PROCESS_CAPABILITY_ALL);
2441         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2442             // No change in capabilities, but TOP_THRESHOLD_STATE change should always be processed.
2443             callOnUidStatechanged(UID_A, TOP_THRESHOLD_STATE, testProcStateSeq++,
2444                     PROCESS_CAPABILITY_ALL);
2445             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2446         }
2447         waitForUidEventHandlerIdle();
2448     }
2449 
2450     @Test
testUidStateChangeAfterUidGone()2451     public void testUidStateChangeAfterUidGone() throws Exception {
2452         final int testProcStateSeq = 51;
2453         final int testProcState = PROCESS_STATE_IMPORTANT_FOREGROUND;
2454 
2455         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2456             // First callback for uid.
2457             callOnUidStatechanged(UID_B, testProcState, testProcStateSeq, PROCESS_CAPABILITY_NONE);
2458             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2459         }
2460         waitForUidEventHandlerIdle();
2461         assertTrue(isUidState(UID_B, testProcState, testProcStateSeq, PROCESS_CAPABILITY_NONE));
2462 
2463         callAndWaitOnUidGone(UID_B);
2464         try (SyncBarrier b = new SyncBarrier(mService.mUidEventHandler)) {
2465             // Even though the procState is the same, the uid had exited - so this should be
2466             // processed as a fresh callback.
2467             callOnUidStatechanged(UID_B, testProcState, testProcStateSeq + 1,
2468                     PROCESS_CAPABILITY_NONE);
2469             assertTrue(mService.mUidEventHandler.hasMessages(UID_MSG_STATE_CHANGED));
2470         }
2471         waitForUidEventHandlerIdle();
2472         assertTrue(isUidState(UID_B, testProcState, testProcStateSeq + 1, PROCESS_CAPABILITY_NONE));
2473     }
2474 
2475     @Test
testObsoleteHandleUidGone()2476     public void testObsoleteHandleUidGone() throws Exception {
2477         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_TOP, 51);
2478         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2479 
2480         clearInvocations(mNetworkManager);
2481 
2482         // In the service, handleUidGone is only called from mUidEventHandler. Then a call to it may
2483         // be rendered obsolete by a newer uid change posted on the handler. The latest uid state
2484         // change is always reflected in the current UidStateChangeCallbackInfo for the uid, so to
2485         // simulate an obsolete call for test, we directly call handleUidGone and leave the state in
2486         // UidStateChangeCallbackInfo set by the previous call to onUidStateChanged(TOP). This call
2487         // should then do nothing.
2488         mService.handleUidGone(UID_A);
2489 
2490         verify(mNetworkManager, times(0)).setFirewallUidRule(anyInt(), anyInt(), anyInt());
2491         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2492     }
2493 
2494     @Test
2495     @RequiresFlagsEnabled(Flags.FLAG_NETWORK_BLOCKED_FOR_TOP_SLEEPING_AND_ABOVE)
testObsoleteHandleUidChanged()2496     public void testObsoleteHandleUidChanged() throws Exception {
2497         callAndWaitOnUidGone(UID_A);
2498         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2499 
2500         clearInvocations(mNetworkManager);
2501 
2502         // In the service, handleUidChanged is only called from mUidEventHandler. Then a call to it
2503         // may be rendered obsolete by an immediate uid-gone posted on the handler. The latest uid
2504         // state change is always reflected in the current UidStateChangeCallbackInfo for the uid,
2505         // so to simulate an obsolete call for test, we directly call handleUidChanged and leave the
2506         // state in UidStateChangeCallbackInfo as null as it would get removed by the previous call
2507         // to onUidGone(). This call should then do nothing.
2508         mService.handleUidChanged(UID_A);
2509 
2510         verify(mNetworkManager, times(0)).setFirewallUidRule(anyInt(), anyInt(), anyInt());
2511         assertTrue(mService.isUidNetworkingBlocked(UID_A, false));
2512     }
2513 
2514     @Test
testLowPowerStandbyAllowlist()2515     public void testLowPowerStandbyAllowlist() throws Exception {
2516         // Chain background is also enabled but these procstates are important enough to be exempt.
2517         callAndWaitOnUidStateChanged(UID_A, PROCESS_STATE_TOP, 0);
2518         callAndWaitOnUidStateChanged(UID_B, ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE, 0);
2519         callAndWaitOnUidStateChanged(UID_C, ActivityManager.PROCESS_STATE_FOREGROUND_SERVICE, 0);
2520         expectHasInternetPermission(UID_A, true);
2521         expectHasInternetPermission(UID_B, true);
2522         expectHasInternetPermission(UID_C, true);
2523 
2524         final NetworkPolicyManagerInternal internal = LocalServices
2525                 .getService(NetworkPolicyManagerInternal.class);
2526 
2527         Map<Integer, Integer> firewallUidRules = new ArrayMap<>();
2528         doAnswer(arg -> {
2529             int[] uids = arg.getArgument(1);
2530             int[] rules = arg.getArgument(2);
2531             assertTrue(uids.length == rules.length);
2532 
2533             for (int i = 0; i < uids.length; ++i) {
2534                 firewallUidRules.put(uids[i], rules[i]);
2535             }
2536             return null;
2537         }).when(mNetworkManager).setFirewallUidRules(eq(FIREWALL_CHAIN_LOW_POWER_STANDBY),
2538                 any(int[].class), any(int[].class));
2539 
2540         internal.setLowPowerStandbyAllowlist(new int[] { UID_B });
2541         internal.setLowPowerStandbyActive(true);
2542         assertEquals(FIREWALL_RULE_ALLOW, firewallUidRules.get(UID_A).intValue());
2543         assertEquals(FIREWALL_RULE_ALLOW, firewallUidRules.get(UID_B).intValue());
2544         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2545         assertFalse(mService.isUidNetworkingBlocked(UID_B, false));
2546         assertTrue(mService.isUidNetworkingBlocked(UID_C, false));
2547 
2548         internal.setLowPowerStandbyActive(false);
2549         assertFalse(mService.isUidNetworkingBlocked(UID_A, false));
2550         assertFalse(mService.isUidNetworkingBlocked(UID_B, false));
2551         assertFalse(mService.isUidNetworkingBlocked(UID_C, false));
2552     }
2553 
2554     @Test
testUpdateEffectiveBlockedReasons()2555     public void testUpdateEffectiveBlockedReasons() {
2556         final Map<Pair<Integer, Integer>, Integer> effectiveBlockedReasons = new HashMap<>();
2557         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_NONE, ALLOWED_REASON_NONE),
2558                 BLOCKED_REASON_NONE);
2559 
2560         effectiveBlockedReasons.put(
2561                 Pair.create(BLOCKED_REASON_BATTERY_SAVER, ALLOWED_REASON_SYSTEM),
2562                 BLOCKED_REASON_NONE);
2563         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_BATTERY_SAVER | BLOCKED_REASON_DOZE,
2564                 ALLOWED_REASON_SYSTEM), BLOCKED_REASON_NONE);
2565         effectiveBlockedReasons.put(
2566                 Pair.create(BLOCKED_METERED_REASON_DATA_SAVER, ALLOWED_METERED_REASON_SYSTEM),
2567                 BLOCKED_REASON_NONE);
2568         effectiveBlockedReasons.put(Pair.create(BLOCKED_METERED_REASON_DATA_SAVER
2569                         | BLOCKED_METERED_REASON_USER_RESTRICTED,
2570                 ALLOWED_METERED_REASON_SYSTEM), BLOCKED_REASON_NONE);
2571 
2572         effectiveBlockedReasons.put(
2573                 Pair.create(BLOCKED_REASON_BATTERY_SAVER | BLOCKED_METERED_REASON_DATA_SAVER,
2574                         ALLOWED_REASON_SYSTEM), BLOCKED_METERED_REASON_DATA_SAVER);
2575         effectiveBlockedReasons.put(
2576                 Pair.create(BLOCKED_REASON_APP_STANDBY | BLOCKED_METERED_REASON_USER_RESTRICTED,
2577                         ALLOWED_METERED_REASON_SYSTEM), BLOCKED_REASON_APP_STANDBY);
2578 
2579         effectiveBlockedReasons.put(
2580                 Pair.create(BLOCKED_REASON_BATTERY_SAVER, ALLOWED_REASON_FOREGROUND),
2581                 BLOCKED_REASON_NONE);
2582         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_BATTERY_SAVER | BLOCKED_REASON_DOZE,
2583                 ALLOWED_REASON_FOREGROUND), BLOCKED_REASON_NONE);
2584         effectiveBlockedReasons.put(
2585                 Pair.create(BLOCKED_METERED_REASON_DATA_SAVER, ALLOWED_METERED_REASON_FOREGROUND),
2586                 BLOCKED_REASON_NONE);
2587         effectiveBlockedReasons.put(Pair.create(BLOCKED_METERED_REASON_DATA_SAVER
2588                         | BLOCKED_METERED_REASON_USER_RESTRICTED,
2589                 ALLOWED_METERED_REASON_FOREGROUND), BLOCKED_REASON_NONE);
2590         effectiveBlockedReasons.put(
2591                 Pair.create(BLOCKED_REASON_BATTERY_SAVER | BLOCKED_METERED_REASON_DATA_SAVER,
2592                         ALLOWED_REASON_FOREGROUND), BLOCKED_METERED_REASON_DATA_SAVER);
2593         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_BATTERY_SAVER
2594                         | BLOCKED_METERED_REASON_USER_RESTRICTED,
2595                 ALLOWED_METERED_REASON_FOREGROUND), BLOCKED_REASON_BATTERY_SAVER);
2596 
2597         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_LOW_POWER_STANDBY,
2598                 ALLOWED_REASON_FOREGROUND), BLOCKED_REASON_LOW_POWER_STANDBY);
2599         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_LOW_POWER_STANDBY,
2600                 ALLOWED_REASON_TOP), BLOCKED_REASON_NONE);
2601         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_LOW_POWER_STANDBY,
2602                 ALLOWED_REASON_LOW_POWER_STANDBY_ALLOWLIST), BLOCKED_REASON_NONE);
2603 
2604         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_APP_BACKGROUND,
2605                 ALLOWED_REASON_NOT_IN_BACKGROUND), BLOCKED_REASON_NONE);
2606         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_APP_BACKGROUND
2607                         | BLOCKED_REASON_BATTERY_SAVER, ALLOWED_REASON_NOT_IN_BACKGROUND),
2608                 BLOCKED_REASON_BATTERY_SAVER);
2609         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_APP_BACKGROUND
2610                         | BLOCKED_REASON_DOZE, ALLOWED_REASON_NOT_IN_BACKGROUND),
2611                 BLOCKED_REASON_DOZE);
2612         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_APP_BACKGROUND,
2613                         ALLOWED_REASON_RESTRICTED_MODE_PERMISSIONS), BLOCKED_REASON_APP_BACKGROUND);
2614         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_APP_BACKGROUND,
2615                 ALLOWED_REASON_POWER_SAVE_ALLOWLIST), BLOCKED_REASON_NONE);
2616         effectiveBlockedReasons.put(Pair.create(BLOCKED_REASON_APP_BACKGROUND,
2617                 ALLOWED_REASON_POWER_SAVE_EXCEPT_IDLE_ALLOWLIST), BLOCKED_REASON_NONE);
2618 
2619         for (Map.Entry<Pair<Integer, Integer>, Integer> test : effectiveBlockedReasons.entrySet()) {
2620             final int expectedEffectiveBlockedReasons = test.getValue();
2621             final int blockedReasons = test.getKey().first;
2622             final int allowedReasons = test.getKey().second;
2623             final String errorMsg = "Expected="
2624                     + blockedReasonsToString(expectedEffectiveBlockedReasons)
2625                     + "; blockedReasons=" + blockedReasonsToString(blockedReasons)
2626                     + ", allowedReasons=" + allowedReasonsToString(allowedReasons);
2627             assertEquals(errorMsg, expectedEffectiveBlockedReasons,
2628                     getEffectiveBlockedReasons(blockedReasons, allowedReasons));
2629         }
2630     }
2631 
2632     @Test
2633     @NetPolicyXml("network-policy-mobile.xml")
testStartToSupportCarrierUsagePolicy()2634     public void testStartToSupportCarrierUsagePolicy() throws Exception {
2635         NetworkPolicy[] policies = mService.getNetworkPolicies(
2636                 mServiceContext.getOpPackageName());
2637         assertEquals("Unexpected number of network policies", 1, policies.length);
2638         NetworkPolicy actualPolicy = policies[0];
2639         assertEquals("Unexpected template match rule in network policies",
2640                 NetworkTemplate.MATCH_CARRIER,
2641                 actualPolicy.template.getMatchRule());
2642         assertTrue("Unexpected subscriberIds size in network policies",
2643                 actualPolicy.template.getSubscriberIds().size() > 0);
2644         assertEquals("Unexpected template meteredness in network policies",
2645                 METERED_YES, actualPolicy.template.getMeteredness());
2646     }
2647 
2648     @Test
2649     @NetPolicyXml("network-policy-wifi-with-subscriberId-match-rule-all-and-templateMetered-no.xml")
testSupportedCarrierUsagePolicy()2650     public void testSupportedCarrierUsagePolicy() throws Exception {
2651         NetworkPolicy[] policies = mService.getNetworkPolicies(
2652                 mServiceContext.getOpPackageName());
2653         assertEquals("Unexpected number of network policies", 1, policies.length);
2654         NetworkPolicy actualPolicy = policies[0];
2655         assertEquals("Unexpected template match rule in network policies",
2656                 MATCH_WIFI,
2657                 actualPolicy.template.getMatchRule());
2658         assertEquals("Unexpected subscriberIds size in network policies",
2659                 actualPolicy.template.getSubscriberIds().size(), 0);
2660         assertEquals("Unexpected template meteredness in network policies",
2661                 METERED_NO, actualPolicy.template.getMeteredness());
2662     }
2663 
2664     @Test
testNormalizeTemplate_duplicatedMergedImsiList()2665     public void testNormalizeTemplate_duplicatedMergedImsiList() {
2666         // This test leads to a Log.wtf, so skip it on eng builds. Otherwise, Log.wtf() would
2667         // result in this process getting killed.
2668         Assume.assumeFalse(Build.IS_ENG);
2669         final NetworkTemplate template = new NetworkTemplate.Builder(MATCH_CARRIER)
2670                 .setSubscriberIds(Set.of(TEST_IMSI)).build();
2671         final String[] mergedImsiGroup = new String[] {TEST_IMSI, TEST_IMSI};
2672         final ArrayList<String[]> mergedList = new ArrayList<>();
2673         mergedList.add(mergedImsiGroup);
2674         // Verify the duplicated items in the merged IMSI list won't crash the system.
2675         final NetworkTemplate result = normalizeTemplate(template, mergedList);
2676         assertEquals(template, result);
2677     }
2678 
formatBlockedStateError(int uid, int rule, boolean metered, boolean backgroundRestricted)2679     private String formatBlockedStateError(int uid, int rule, boolean metered,
2680             boolean backgroundRestricted) {
2681         return String.format(
2682                 "Unexpected BlockedState: (uid=%d, rule=%s, metered=%b, backgroundRestricted=%b)",
2683                 uid, uidRulesToString(rule), metered, backgroundRestricted);
2684     }
2685 
buildMonthlyDataPlan(ZonedDateTime start, long limitBytes)2686     private SubscriptionPlan buildMonthlyDataPlan(ZonedDateTime start, long limitBytes) {
2687         return SubscriptionPlan.Builder
2688                 .createRecurringMonthly(start)
2689                 .setDataLimit(limitBytes, LIMIT_BEHAVIOR_DISABLED)
2690                 .build();
2691     }
2692 
buildApplicationInfo(String label, int uid)2693     private ApplicationInfo buildApplicationInfo(String label, int uid) {
2694         final ApplicationInfo ai = new ApplicationInfo();
2695         ai.nonLocalizedLabel = label;
2696         ai.uid = uid;
2697         return ai;
2698     }
2699 
buildInstalledPackageList()2700     private List<AndroidPackage> buildInstalledPackageList() {
2701         final List<AndroidPackage> installedApps = new ArrayList<>();
2702         installedApps.add(createPackageMock(UID_A));
2703         installedApps.add(createPackageMock(UID_B));
2704         installedApps.add(createPackageMock(UID_C));
2705         return installedApps;
2706     }
2707 
createPackageMock(int uid)2708     private AndroidPackage createPackageMock(int uid) {
2709         final AndroidPackage androidPackage = mock(AndroidPackage.class);
2710         when(androidPackage.getUid()).thenReturn(uid);
2711         return androidPackage;
2712     }
2713 
buildUserInfoList()2714     private List<UserInfo> buildUserInfoList() {
2715         final List<UserInfo> users = new ArrayList<>();
2716         users.add(new UserInfo(USER_ID, "user1", 0));
2717         return users;
2718     }
2719 
buildLinkProperties(String iface)2720     private LinkProperties buildLinkProperties(String iface) {
2721         final LinkProperties lp = new LinkProperties();
2722         lp.setInterfaceName(iface);
2723         return lp;
2724     }
2725 
buildNetworkCapabilities(int subId, boolean roaming)2726     private NetworkCapabilities buildNetworkCapabilities(int subId, boolean roaming) {
2727         final NetworkCapabilities.Builder builder = new NetworkCapabilities.Builder();
2728         builder.addTransportType(TRANSPORT_CELLULAR);
2729         if (!roaming) {
2730             builder.addCapability(NET_CAPABILITY_NOT_ROAMING);
2731         }
2732         builder.setNetworkSpecifier(new TelephonyNetworkSpecifier.Builder()
2733                 .setSubscriptionId(subId).build());
2734         return builder.build();
2735     }
2736 
buildDefaultFakeCarrierPolicy()2737     private NetworkPolicy buildDefaultFakeCarrierPolicy() {
2738         NetworkPolicy p = mService.buildDefaultCarrierPolicy(FAKE_SUB_ID, FAKE_SUBSCRIBER_ID);
2739         // set a deterministic cycle date
2740         p.cycleRule = new RecurrenceRule(
2741                 p.cycleRule.start.withDayOfMonth(DEFAULT_CYCLE_DAY),
2742                 p.cycleRule.end, Period.ofMonths(1));
2743         return p;
2744     }
2745 
buildFakeCarrierPolicy(int cycleDay, long warningBytes, long limitBytes, boolean inferred)2746     private static NetworkPolicy buildFakeCarrierPolicy(int cycleDay, long warningBytes,
2747             long limitBytes, boolean inferred) {
2748         // TODO: Refactor this to use sTemplateCarrierMetered.
2749         final NetworkTemplate template = new NetworkTemplate.Builder(MATCH_CARRIER)
2750                 .setSubscriberIds(Set.of(FAKE_SUBSCRIBER_ID))
2751                 .setMeteredness(METERED_YES).build();
2752         return new NetworkPolicy(template, cycleDay, TimeZone.getDefault().getID(), warningBytes,
2753                 limitBytes, SNOOZE_NEVER, SNOOZE_NEVER, true, inferred);
2754     }
2755 
assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes, long expectedLimitBytes, boolean expectedInferred)2756     private void assertNetworkPolicyEquals(int expectedCycleDay, long expectedWarningBytes,
2757             long expectedLimitBytes, boolean expectedInferred) {
2758         NetworkPolicy[] policies = mService.getNetworkPolicies(
2759                 mServiceContext.getOpPackageName());
2760         assertEquals("Unexpected number of network policies", 1, policies.length);
2761         NetworkPolicy actualPolicy = policies[0];
2762         NetworkPolicy expectedPolicy = buildFakeCarrierPolicy(expectedCycleDay,
2763                 expectedWarningBytes, expectedLimitBytes, expectedInferred);
2764         assertEquals(expectedPolicy, actualPolicy);
2765     }
2766 
parseTime(String time)2767     private static long parseTime(String time) {
2768         return ZonedDateTime.parse(time).toInstant().toEpochMilli();
2769     }
2770 
setNetworkPolicies(NetworkPolicy... policies)2771     private void setNetworkPolicies(NetworkPolicy... policies) {
2772         mService.setNetworkPolicies(policies);
2773     }
2774 
buildWifi()2775     private static NetworkStateSnapshot buildWifi() {
2776         WifiInfo mockWifiInfo = mock(WifiInfo.class);
2777         when(mockWifiInfo.makeCopy(anyLong())).thenReturn(mockWifiInfo);
2778         when(mockWifiInfo.getNetworkKey()).thenReturn(TEST_WIFI_NETWORK_KEY);
2779         final LinkProperties prop = new LinkProperties();
2780         prop.setInterfaceName(TEST_IFACE);
2781         final NetworkCapabilities networkCapabilities = new NetworkCapabilities.Builder()
2782                 .addTransportType(TRANSPORT_WIFI).setTransportInfo(mockWifiInfo).build();
2783         return new NetworkStateSnapshot(TEST_NETWORK, networkCapabilities, prop,
2784                 null /*subscriberId*/, TYPE_WIFI);
2785     }
2786 
expectHasInternetPermission(int uid, boolean hasIt)2787     private void expectHasInternetPermission(int uid, boolean hasIt) throws Exception {
2788         when(mIpm.checkUidPermission(Manifest.permission.INTERNET, uid)).thenReturn(
2789                 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
2790     }
2791 
expectHasUseRestrictedNetworksPermission(int uid, boolean hasIt)2792     private void expectHasUseRestrictedNetworksPermission(int uid, boolean hasIt) throws Exception {
2793         when(mIpm.checkUidPermission(CONNECTIVITY_USE_RESTRICTED_NETWORKS, uid)).thenReturn(
2794                 hasIt ? PackageManager.PERMISSION_GRANTED : PackageManager.PERMISSION_DENIED);
2795         when(mIpm.checkUidPermission(NETWORK_STACK, uid)).thenReturn(
2796                 PackageManager.PERMISSION_DENIED);
2797         when(mIpm.checkUidPermission(PERMISSION_MAINLINE_NETWORK_STACK, uid)).thenReturn(
2798                 PackageManager.PERMISSION_DENIED);
2799     }
2800 
expectNetworkStateSnapshot(boolean roaming)2801     private void expectNetworkStateSnapshot(boolean roaming) throws Exception {
2802         when(mCarrierConfigManager.getConfigForSubId(eq(TEST_SUB_ID)))
2803                 .thenReturn(mCarrierConfig);
2804         List<NetworkStateSnapshot> snapshots = List.of(new NetworkStateSnapshot(
2805                 TEST_NETWORK,
2806                 buildNetworkCapabilities(TEST_SUB_ID, roaming),
2807                 buildLinkProperties(TEST_IFACE), TEST_IMSI, TYPE_MOBILE));
2808         when(mConnManager.getAllNetworkStateSnapshots()).thenReturn(snapshots);
2809     }
2810 
expectDefaultCarrierConfig()2811     private void expectDefaultCarrierConfig() throws Exception {
2812         when(mCarrierConfigManager.getConfigForSubId(eq(TEST_SUB_ID)))
2813                 .thenReturn(CarrierConfigManager.getDefaultConfig());
2814     }
2815 
expectMobileDefaults()2816     private TelephonyManager expectMobileDefaults() throws Exception {
2817         TelephonyManager tmSub = setupTelephonySubscriptionManagers(TEST_SUB_ID, TEST_IMSI);
2818         doNothing().when(tmSub).setPolicyDataEnabled(anyBoolean());
2819         expectNetworkStateSnapshot(false /* roaming */);
2820         return tmSub;
2821     }
2822 
verifyAdvisePersistThreshold()2823     private void verifyAdvisePersistThreshold() throws Exception {
2824         verify(mStatsManager).setDefaultGlobalAlert(anyLong());
2825     }
2826 
assertTimeEquals(long expected, long actual)2827     private static void assertTimeEquals(long expected, long actual) {
2828         if (expected != actual) {
2829             fail("expected " + formatTime(expected) + " but was actually " + formatTime(actual));
2830         }
2831     }
2832 
formatTime(long millis)2833     private static String formatTime(long millis) {
2834         return Instant.ofEpochMilli(millis) + " [" + millis + "]";
2835     }
2836 
assertEqualsFuzzy(long expected, long actual, long fuzzy)2837     private static void assertEqualsFuzzy(long expected, long actual, long fuzzy) {
2838         final long low = expected - fuzzy;
2839         final long high = expected + fuzzy;
2840         if (actual < low || actual > high) {
2841             fail("value " + formatTime(actual) + " is outside [" + formatTime(low) + ","
2842                     + formatTime(high) + "]");
2843         }
2844     }
2845 
assertUnique(LinkedHashSet<Long> seen, Long value)2846     private static void assertUnique(LinkedHashSet<Long> seen, Long value) {
2847         if (!seen.add(value)) {
2848             fail("found duplicate time " + value + " in series " + seen.toString());
2849         }
2850     }
2851 
assertNotificationType(int expected, String actualTag)2852     private static void assertNotificationType(int expected, String actualTag) {
2853         assertEquals("notification type mismatch for '" + actualTag + "'",
2854                 Integer.toString(expected), actualTag.substring(actualTag.lastIndexOf(':') + 1));
2855     }
2856 
assertUidPolicy(int uid, int expected)2857     private void assertUidPolicy(int uid, int expected) {
2858         final int actual = mService.getUidPolicy(uid);
2859         if (expected != actual) {
2860             fail("Wrong policy for UID " + uid + ": expected " + uidPoliciesToString(expected)
2861                     + ", actual " + uidPoliciesToString(actual));
2862         }
2863     }
2864 
assertRestrictBackgroundAllowedUids(int... uids)2865     private void assertRestrictBackgroundAllowedUids(int... uids) {
2866         assertContainsInAnyOrder(mService.getUidsWithPolicy(POLICY_ALLOW_METERED_BACKGROUND), uids);
2867     }
2868 
assertRestrictBackgroundOn()2869     private void assertRestrictBackgroundOn() throws Exception {
2870         assertTrue("restrictBackground should be set", mService.getRestrictBackground());
2871     }
2872 
assertRestrictBackgroundOff()2873     private void assertRestrictBackgroundOff() throws Exception {
2874         assertFalse("restrictBackground should not be set", mService.getRestrictBackground());
2875     }
2876 
newRestrictBackgroundChangedFuture()2877     private FutureIntent newRestrictBackgroundChangedFuture() {
2878         return mServiceContext
2879                 .nextBroadcastIntent(ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED);
2880     }
2881 
assertRestrictBackgroundChangedReceived(Future<Intent> future, String expectedPackage)2882     private void assertRestrictBackgroundChangedReceived(Future<Intent> future,
2883             String expectedPackage) throws Exception {
2884         final String action = ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
2885         final Intent intent = future.get(5, TimeUnit.SECONDS);
2886         assertNotNull("Didn't get a " + action + "intent in 5 seconds");
2887         assertEquals("Wrong package on " + action + " intent",
2888                 expectedPackage, intent.getPackage());
2889     }
2890 
2891     // TODO: replace by Truth, Hamcrest, or a similar tool.
assertContainsInAnyOrder(int[] actual, int...expected)2892     private void assertContainsInAnyOrder(int[] actual, int...expected) {
2893         final StringBuilder errors = new StringBuilder();
2894         if (actual.length != expected.length) {
2895             errors.append("\tsize does not match\n");
2896         }
2897         final List<Integer> actualList =
2898                 Arrays.stream(actual).boxed().collect(Collectors.<Integer>toList());
2899         final List<Integer> expectedList =
2900                 Arrays.stream(expected).boxed().collect(Collectors.<Integer>toList());
2901         if (!actualList.containsAll(expectedList)) {
2902             errors.append("\tmissing elements on actual list\n");
2903         }
2904         if (!expectedList.containsAll(actualList)) {
2905             errors.append("\tmissing elements on expected list\n");
2906         }
2907         if (errors.length() > 0) {
2908             fail("assertContainsInAnyOrder(expected=" + Arrays.toString(expected)
2909                     + ", actual=" + Arrays.toString(actual) + ") failed: \n" + errors);
2910         }
2911     }
2912 
getElapsedRealtime()2913     private long getElapsedRealtime() {
2914         return mElapsedRealtime;
2915     }
2916 
setCurrentTimeMillis(long currentTimeMillis)2917     private void setCurrentTimeMillis(long currentTimeMillis) {
2918         RecurrenceRule.sClock = Clock.fixed(Instant.ofEpochMilli(currentTimeMillis),
2919                 ZoneId.systemDefault());
2920         mStartTime = currentTimeMillis;
2921         mElapsedRealtime = 0L;
2922     }
2923 
currentTimeMillis()2924     private long currentTimeMillis() {
2925         return mStartTime + mElapsedRealtime;
2926     }
2927 
incrementCurrentTime(long duration)2928     private void incrementCurrentTime(long duration) {
2929         mElapsedRealtime += duration;
2930     }
2931 
2932     private FutureIntent mRestrictBackgroundChanged;
2933 
postMsgAndWaitForCompletion()2934     private void postMsgAndWaitForCompletion() throws InterruptedException {
2935         final CountDownLatch latch = new CountDownLatch(1);
2936         mService.getHandlerForTesting().post(latch::countDown);
2937         if (!latch.await(5, TimeUnit.SECONDS)) {
2938             fail("Timed out waiting for the test msg to be handled");
2939         }
2940     }
2941 
2942     /**
2943      * This posts a blocking message to the service handler with the given delayMs and waits for it
2944      * to complete. This ensures that all messages posted before the given delayMs will also
2945      * have been executed before this method returns and can be verified in subsequent code.
2946      */
waitForDelayedMessageOnHandler(long delayMs)2947     private void waitForDelayedMessageOnHandler(long delayMs) throws InterruptedException {
2948         final CountDownLatch latch = new CountDownLatch(1);
2949         mService.getHandlerForTesting().postDelayed(latch::countDown, delayMs);
2950         if (!latch.await(delayMs + 5_000, TimeUnit.MILLISECONDS)) {
2951             fail("Timed out waiting for delayed msg to be handled");
2952         }
2953     }
2954 
setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage)2955     private void setSubscriptionPlans(int subId, SubscriptionPlan[] plans, String callingPackage)
2956             throws InterruptedException {
2957         mService.setSubscriptionPlans(subId, plans, 0, callingPackage);
2958         // setSubscriptionPlans() triggers async events, wait for those to be completed before
2959         // moving forward as they could interfere with the tests later.
2960         postMsgAndWaitForCompletion();
2961     }
2962 
setRestrictBackground(boolean flag)2963     private void setRestrictBackground(boolean flag) throws Exception {
2964         mService.setRestrictBackground(flag);
2965         assertEquals("restrictBackground not set", flag, mService.getRestrictBackground());
2966     }
2967 
2968     /**
2969      * Creates a mock and registers it to {@link LocalServices}.
2970      */
addLocalServiceMock(Class<T> clazz)2971     private static <T> T addLocalServiceMock(Class<T> clazz) {
2972         final T mock = mock(clazz);
2973         LocalServices.addService(clazz, mock);
2974         return mock;
2975     }
2976 
2977     /**
2978      * Creates a mock {@link TelephonyManager} and {@link SubscriptionManager}.
2979      *
2980      */
setupTelephonySubscriptionManagers(int subscriptionId, String subscriberId)2981     private TelephonyManager setupTelephonySubscriptionManagers(int subscriptionId,
2982             String subscriberId) {
2983         when(mSubscriptionManager.getActiveSubscriptionInfoList()).thenReturn(
2984                 createSubscriptionInfoList(subscriptionId));
2985         notifyDefaultAndActiveDataSubIdChange(subscriptionId, subscriptionId);
2986 
2987         TelephonyManager subTelephonyManager;
2988         subTelephonyManager = mock(TelephonyManager.class);
2989         when(subTelephonyManager.getSubscriptionId()).thenReturn(subscriptionId);
2990         when(subTelephonyManager.getSubscriberId()).thenReturn(subscriberId);
2991         when(mTelephonyManager.createForSubscriptionId(subscriptionId))
2992                 .thenReturn(subTelephonyManager);
2993         return subTelephonyManager;
2994     }
2995 
2996     /**
2997      * Telephony Manager callback notifies data sub Id changes.
2998      * @param defaultDataSubId The mock default data sub Id.
2999      * @param activeDataSubId The mock active data sub Id.
3000      */
notifyDefaultAndActiveDataSubIdChange(int defaultDataSubId, int activeDataSubId)3001     private void notifyDefaultAndActiveDataSubIdChange(int defaultDataSubId, int activeDataSubId) {
3002         mDeps.setDefaultAndActiveDataSubId(defaultDataSubId, activeDataSubId);
3003         mActiveDataSubIdListener.onActiveDataSubscriptionIdChanged(activeDataSubId);
3004     }
3005 
3006     /**
3007      * Creates mock {@link SubscriptionInfo} from subscription id.
3008      */
createSubscriptionInfoList(int subId)3009     private List<SubscriptionInfo> createSubscriptionInfoList(int subId) {
3010         final List<SubscriptionInfo> sub = new ArrayList<>();
3011         sub.add(createSubscriptionInfo(subId));
3012         return sub;
3013     }
3014 
3015     /**
3016      * Creates mock {@link SubscriptionInfo} from subscription id.
3017      */
createSubscriptionInfo(int subId)3018     private SubscriptionInfo createSubscriptionInfo(int subId) {
3019         return new SubscriptionInfo(subId, null, -1, null, null, -1, -1,
3020                 null, -1, null, null, null, null, false, null, null);
3021     }
3022 
3023     /**
3024      * Custom Mockito answer used to verify async {@link INetworkPolicyListener} calls.
3025      *
3026      * <p>Typical usage:
3027      * <pre><code>
3028      *    mPolicyListener.expect().someCallback(any());
3029      *    // do something on objects under test
3030      *    mPolicyListener.waitAndVerify().someCallback(eq(expectedValue));
3031      * </code></pre>
3032      */
3033     final class NetworkPolicyListenerAnswer implements Answer<Void> {
3034         private CountDownLatch latch;
3035         private final INetworkPolicyListener listener;
3036 
NetworkPolicyListenerAnswer(NetworkPolicyManagerService service)3037         NetworkPolicyListenerAnswer(NetworkPolicyManagerService service) {
3038             this.listener = mock(INetworkPolicyListener.class);
3039             // RemoteCallbackList needs a binder to use as key
3040             when(listener.asBinder()).thenReturn(new Binder());
3041             service.registerListener(listener);
3042         }
3043 
3044         @Override
answer(InvocationOnMock invocation)3045         public Void answer(InvocationOnMock invocation) throws Throwable {
3046             Log.d(TAG, "counting down on answer: " + invocation);
3047             latch.countDown();
3048             return null;
3049         }
3050 
expect()3051         INetworkPolicyListener expect() {
3052             assertNull("expect() called before waitAndVerify()", latch);
3053             latch = new CountDownLatch(1);
3054             return doAnswer(this).when(listener);
3055         }
3056 
waitAndVerify()3057         INetworkPolicyListener waitAndVerify() {
3058             assertNotNull("waitAndVerify() called before expect()", latch);
3059             try {
3060                 assertTrue("callback not called in 5 seconds", latch.await(5, TimeUnit.SECONDS));
3061             } catch (InterruptedException e) {
3062                 fail("Thread interrupted before callback called");
3063             } finally {
3064                 latch = null;
3065             }
3066             return verify(listener, atLeastOnce());
3067         }
3068 
verifyNotCalled()3069         INetworkPolicyListener verifyNotCalled() {
3070             return verify(listener, never());
3071         }
3072 
3073     }
3074 
setNetpolicyXml(Context context)3075     private void setNetpolicyXml(Context context) throws Exception {
3076         mPolicyDir = context.getFilesDir();
3077         if (mPolicyDir.exists()) {
3078             FsUtil.deleteContents(mPolicyDir);
3079         }
3080         if (!TextUtils.isEmpty(mNetpolicyXml)) {
3081             final String assetPath = NETPOLICY_DIR + "/" + mNetpolicyXml;
3082             final File netConfigFile = new File(mPolicyDir, "netpolicy.xml");
3083             Log.d(TAG, "Creating " + netConfigFile + " from asset " + assetPath);
3084             try (InputStream in = context.getResources().getAssets().open(assetPath);
3085                     OutputStream out = new FileOutputStream(netConfigFile)) {
3086                 Streams.copy(in, out);
3087             }
3088         }
3089     }
3090 
3091     /**
3092      * Annotation used to define the relative path of the {@code netpolicy.xml} file.
3093      */
3094     @Retention(RetentionPolicy.RUNTIME)
3095     @Target(ElementType.METHOD)
3096     public @interface NetPolicyXml {
value()3097         String value() default "";
3098     }
3099 
3100     /**
3101      * Rule used to set {@code mNetPolicyXml} according to the {@link NetPolicyXml} annotation.
3102      */
3103     public static class NetPolicyMethodRule implements MethodRule {
3104 
3105         @Override
apply(Statement base, FrameworkMethod method, Object target)3106         public Statement apply(Statement base, FrameworkMethod method, Object target) {
3107             for (Annotation annotation : method.getAnnotations()) {
3108                 if ((annotation instanceof NetPolicyXml)) {
3109                     final String path = ((NetPolicyXml) annotation).value();
3110                     if (!path.isEmpty()) {
3111                         ((NetworkPolicyManagerServiceTest) target).mNetpolicyXml = path;
3112                         break;
3113                     }
3114                 }
3115             }
3116             return base;
3117         }
3118     }
3119 }
3120