1 /*
2  * Copyright (C) 2017 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 android.net;
18 
19 import static android.net.NetworkCapabilities.LINK_BANDWIDTH_UNSPECIFIED;
20 import static android.net.NetworkCapabilities.MAX_TRANSPORT;
21 import static android.net.NetworkCapabilities.MIN_TRANSPORT;
22 import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
23 import static android.net.NetworkCapabilities.NET_CAPABILITY_CBS;
24 import static android.net.NetworkCapabilities.NET_CAPABILITY_DUN;
25 import static android.net.NetworkCapabilities.NET_CAPABILITY_EIMS;
26 import static android.net.NetworkCapabilities.NET_CAPABILITY_ENTERPRISE;
27 import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
28 import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29 import static android.net.NetworkCapabilities.NET_CAPABILITY_LOCAL_NETWORK;
30 import static android.net.NetworkCapabilities.NET_CAPABILITY_MMS;
31 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
32 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
33 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
34 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VCN_MANAGED;
35 import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
36 import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PAID;
37 import static android.net.NetworkCapabilities.NET_CAPABILITY_OEM_PRIVATE;
38 import static android.net.NetworkCapabilities.NET_CAPABILITY_PARTIAL_CONNECTIVITY;
39 import static android.net.NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_BANDWIDTH;
40 import static android.net.NetworkCapabilities.NET_CAPABILITY_PRIORITIZE_LATENCY;
41 import static android.net.NetworkCapabilities.NET_CAPABILITY_RCS;
42 import static android.net.NetworkCapabilities.NET_CAPABILITY_SUPL;
43 import static android.net.NetworkCapabilities.NET_CAPABILITY_TRUSTED;
44 import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
45 import static android.net.NetworkCapabilities.NET_CAPABILITY_WIFI_P2P;
46 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_1;
47 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_2;
48 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_3;
49 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_4;
50 import static android.net.NetworkCapabilities.NET_ENTERPRISE_ID_5;
51 import static android.net.NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION;
52 import static android.net.NetworkCapabilities.REDACT_FOR_LOCAL_MAC_ADDRESS;
53 import static android.net.NetworkCapabilities.REDACT_FOR_NETWORK_SETTINGS;
54 import static android.net.NetworkCapabilities.SIGNAL_STRENGTH_UNSPECIFIED;
55 import static android.net.NetworkCapabilities.TRANSPORT_CELLULAR;
56 import static android.net.NetworkCapabilities.TRANSPORT_ETHERNET;
57 import static android.net.NetworkCapabilities.TRANSPORT_SATELLITE;
58 import static android.net.NetworkCapabilities.TRANSPORT_TEST;
59 import static android.net.NetworkCapabilities.TRANSPORT_USB;
60 import static android.net.NetworkCapabilities.TRANSPORT_VPN;
61 import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
62 import static android.net.NetworkCapabilities.TRANSPORT_WIFI_AWARE;
63 import static android.os.Process.INVALID_UID;
64 
65 import static com.android.modules.utils.build.SdkLevel.isAtLeastS;
66 import static com.android.modules.utils.build.SdkLevel.isAtLeastT;
67 import static com.android.modules.utils.build.SdkLevel.isAtLeastV;
68 import static com.android.testutils.DevSdkIgnoreRuleKt.SC_V2;
69 import static com.android.testutils.MiscAsserts.assertEmpty;
70 import static com.android.testutils.MiscAsserts.assertThrows;
71 import static com.android.testutils.ParcelUtils.assertParcelingIsLossless;
72 
73 import static org.junit.Assert.assertArrayEquals;
74 import static org.junit.Assert.assertEquals;
75 import static org.junit.Assert.assertFalse;
76 import static org.junit.Assert.assertNotEquals;
77 import static org.junit.Assert.assertNull;
78 import static org.junit.Assert.assertTrue;
79 import static org.junit.Assert.fail;
80 import static org.junit.Assume.assumeTrue;
81 
82 import android.net.wifi.aware.DiscoverySession;
83 import android.net.wifi.aware.PeerHandle;
84 import android.net.wifi.aware.WifiAwareNetworkSpecifier;
85 import android.os.Build;
86 import android.util.ArraySet;
87 import android.util.Range;
88 
89 import androidx.test.filters.SmallTest;
90 
91 import com.android.testutils.CompatUtil;
92 import com.android.testutils.ConnectivityModuleTest;
93 import com.android.testutils.DevSdkIgnoreRule;
94 import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo;
95 import com.android.testutils.DevSdkIgnoreRunner;
96 
97 import org.junit.Rule;
98 import org.junit.Test;
99 import org.junit.runner.RunWith;
100 import org.mockito.Mockito;
101 
102 import java.util.ArrayList;
103 import java.util.Arrays;
104 import java.util.List;
105 import java.util.Set;
106 
107 @SmallTest
108 @RunWith(DevSdkIgnoreRunner.class)
109 // NetworkCapabilities is only updatable on S+, and this test covers behavior which implementation
110 // is self-contained within NetworkCapabilities.java, so it does not need to be run on, or
111 // compatible with, earlier releases.
112 @IgnoreUpTo(Build.VERSION_CODES.R)
113 @ConnectivityModuleTest
114 public class NetworkCapabilitiesTest {
115     private static final String TEST_SSID = "TEST_SSID";
116     private static final String DIFFERENT_TEST_SSID = "DIFFERENT_TEST_SSID";
117     private static final int TEST_SUBID1 = 1;
118     private static final int TEST_SUBID2 = 2;
119     private static final int TEST_SUBID3 = 3;
120 
121     private static final Set<Integer> TEST_NETWORKS_EXTRA_ALLOWED_CAPS_ON_NON_CELL =
122             Set.of(NET_CAPABILITY_CBS, NET_CAPABILITY_DUN, NET_CAPABILITY_RCS);
123 
124     @Rule
125     public DevSdkIgnoreRule mDevSdkIgnoreRule = new DevSdkIgnoreRule();
126 
127     private DiscoverySession mDiscoverySession = Mockito.mock(DiscoverySession.class);
128     private PeerHandle mPeerHandle = Mockito.mock(PeerHandle.class);
129 
130     @Test
testMaybeMarkCapabilitiesRestricted()131     public void testMaybeMarkCapabilitiesRestricted() {
132         // check that internet does not get restricted
133         NetworkCapabilities netCap = new NetworkCapabilities();
134         netCap.addCapability(NET_CAPABILITY_INTERNET);
135         netCap.maybeMarkCapabilitiesRestricted();
136         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
137 
138         // metered-ness shouldn't matter
139         netCap = new NetworkCapabilities();
140         netCap.addCapability(NET_CAPABILITY_INTERNET);
141         netCap.addCapability(NET_CAPABILITY_NOT_METERED);
142         netCap.maybeMarkCapabilitiesRestricted();
143         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
144         netCap = new NetworkCapabilities();
145         netCap.addCapability(NET_CAPABILITY_INTERNET);
146         netCap.removeCapability(NET_CAPABILITY_NOT_METERED);
147         netCap.maybeMarkCapabilitiesRestricted();
148         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
149 
150         // add EIMS - bundled with unrestricted means it's unrestricted
151         netCap = new NetworkCapabilities();
152         netCap.addCapability(NET_CAPABILITY_INTERNET);
153         netCap.addCapability(NET_CAPABILITY_EIMS);
154         netCap.addCapability(NET_CAPABILITY_NOT_METERED);
155         netCap.maybeMarkCapabilitiesRestricted();
156         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
157         netCap = new NetworkCapabilities();
158         netCap.addCapability(NET_CAPABILITY_INTERNET);
159         netCap.addCapability(NET_CAPABILITY_EIMS);
160         netCap.removeCapability(NET_CAPABILITY_NOT_METERED);
161         netCap.maybeMarkCapabilitiesRestricted();
162         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
163 
164         // just a restricted cap should be restricted regardless of meteredness
165         netCap = new NetworkCapabilities();
166         netCap.addCapability(NET_CAPABILITY_EIMS);
167         netCap.addCapability(NET_CAPABILITY_NOT_METERED);
168         netCap.maybeMarkCapabilitiesRestricted();
169         assertFalse(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
170         netCap = new NetworkCapabilities();
171         netCap.addCapability(NET_CAPABILITY_EIMS);
172         netCap.removeCapability(NET_CAPABILITY_NOT_METERED);
173         netCap.maybeMarkCapabilitiesRestricted();
174         assertFalse(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
175 
176         // try 2 restricted caps
177         netCap = new NetworkCapabilities();
178         netCap.addCapability(NET_CAPABILITY_CBS);
179         netCap.addCapability(NET_CAPABILITY_EIMS);
180         netCap.addCapability(NET_CAPABILITY_NOT_METERED);
181         netCap.maybeMarkCapabilitiesRestricted();
182         assertFalse(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
183         netCap = new NetworkCapabilities();
184         netCap.addCapability(NET_CAPABILITY_CBS);
185         netCap.addCapability(NET_CAPABILITY_EIMS);
186         netCap.removeCapability(NET_CAPABILITY_NOT_METERED);
187         netCap.maybeMarkCapabilitiesRestricted();
188         assertFalse(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
189     }
190 
191     @Test
testDescribeImmutableDifferences()192     public void testDescribeImmutableDifferences() {
193         NetworkCapabilities nc1;
194         NetworkCapabilities nc2;
195 
196         // Transports changing
197         nc1 = new NetworkCapabilities().addTransportType(TRANSPORT_CELLULAR);
198         nc2 = new NetworkCapabilities().addTransportType(TRANSPORT_WIFI);
199         assertNotEquals("", nc1.describeImmutableDifferences(nc2));
200         assertEquals("", nc1.describeImmutableDifferences(nc1));
201 
202         // Mutable capability changing
203         nc1 = new NetworkCapabilities().addCapability(NET_CAPABILITY_VALIDATED);
204         nc2 = new NetworkCapabilities();
205         assertEquals("", nc1.describeImmutableDifferences(nc2));
206         assertEquals("", nc1.describeImmutableDifferences(nc1));
207 
208         // NOT_METERED changing (http://b/63326103)
209         nc1 = new NetworkCapabilities()
210                 .addCapability(NET_CAPABILITY_NOT_METERED)
211                 .addCapability(NET_CAPABILITY_INTERNET);
212         nc2 = new NetworkCapabilities().addCapability(NET_CAPABILITY_INTERNET);
213         assertEquals("", nc1.describeImmutableDifferences(nc2));
214         assertEquals("", nc1.describeImmutableDifferences(nc1));
215 
216         // Immutable capability changing
217         nc1 = new NetworkCapabilities()
218                 .addCapability(NET_CAPABILITY_INTERNET)
219                 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
220         nc2 = new NetworkCapabilities().addCapability(NET_CAPABILITY_INTERNET);
221         assertNotEquals("", nc1.describeImmutableDifferences(nc2));
222         assertEquals("", nc1.describeImmutableDifferences(nc1));
223 
224         // Specifier changing
225         nc1 = new NetworkCapabilities().addTransportType(TRANSPORT_WIFI);
226         nc2 = new NetworkCapabilities()
227                 .addTransportType(TRANSPORT_WIFI)
228                 .setNetworkSpecifier(CompatUtil.makeEthernetNetworkSpecifier("eth42"));
229         assertNotEquals("", nc1.describeImmutableDifferences(nc2));
230         assertEquals("", nc1.describeImmutableDifferences(nc1));
231     }
232 
233     @Test
testLinkBandwidthUtils()234     public void testLinkBandwidthUtils() {
235         assertEquals(LINK_BANDWIDTH_UNSPECIFIED, NetworkCapabilities
236                 .minBandwidth(LINK_BANDWIDTH_UNSPECIFIED, LINK_BANDWIDTH_UNSPECIFIED));
237         assertEquals(10, NetworkCapabilities
238                 .minBandwidth(LINK_BANDWIDTH_UNSPECIFIED, 10));
239         assertEquals(10, NetworkCapabilities
240                 .minBandwidth(10, LINK_BANDWIDTH_UNSPECIFIED));
241         assertEquals(10, NetworkCapabilities
242                 .minBandwidth(10, 20));
243 
244         assertEquals(LINK_BANDWIDTH_UNSPECIFIED, NetworkCapabilities
245                 .maxBandwidth(LINK_BANDWIDTH_UNSPECIFIED, LINK_BANDWIDTH_UNSPECIFIED));
246         assertEquals(10, NetworkCapabilities
247                 .maxBandwidth(LINK_BANDWIDTH_UNSPECIFIED, 10));
248         assertEquals(10, NetworkCapabilities
249                 .maxBandwidth(10, LINK_BANDWIDTH_UNSPECIFIED));
250         assertEquals(20, NetworkCapabilities
251                 .maxBandwidth(10, 20));
252     }
253 
254     @Test
testSetUids()255     public void testSetUids() {
256         final NetworkCapabilities netCap = new NetworkCapabilities();
257         // Null uids match all UIDs
258         netCap.setUids(null);
259         assertTrue(netCap.appliesToUid(10));
260         assertTrue(netCap.appliesToUid(200));
261         assertTrue(netCap.appliesToUid(3000));
262         assertTrue(netCap.appliesToUid(10010));
263         assertTrue(netCap.appliesToUidRange(new UidRange(50, 100)));
264         assertTrue(netCap.appliesToUidRange(new UidRange(70, 72)));
265         assertTrue(netCap.appliesToUidRange(new UidRange(3500, 3912)));
266         assertTrue(netCap.appliesToUidRange(new UidRange(1, 100000)));
267 
268         if (isAtLeastS()) {
269             final Set<Range<Integer>> uids = new ArraySet<>();
270             uids.add(uidRange(50, 100));
271             uids.add(uidRange(3000, 4000));
272             netCap.setUids(uids);
273             assertTrue(netCap.appliesToUid(50));
274             assertTrue(netCap.appliesToUid(80));
275             assertTrue(netCap.appliesToUid(100));
276             assertTrue(netCap.appliesToUid(3000));
277             assertTrue(netCap.appliesToUid(3001));
278             assertFalse(netCap.appliesToUid(10));
279             assertFalse(netCap.appliesToUid(25));
280             assertFalse(netCap.appliesToUid(49));
281             assertFalse(netCap.appliesToUid(101));
282             assertFalse(netCap.appliesToUid(2000));
283             assertFalse(netCap.appliesToUid(100000));
284 
285             assertTrue(netCap.appliesToUidRange(new UidRange(50, 100)));
286             assertTrue(netCap.appliesToUidRange(new UidRange(70, 72)));
287             assertTrue(netCap.appliesToUidRange(new UidRange(3500, 3912)));
288             assertFalse(netCap.appliesToUidRange(new UidRange(1, 100)));
289             assertFalse(netCap.appliesToUidRange(new UidRange(49, 100)));
290             assertFalse(netCap.appliesToUidRange(new UidRange(1, 10)));
291             assertFalse(netCap.appliesToUidRange(new UidRange(60, 101)));
292             assertFalse(netCap.appliesToUidRange(new UidRange(60, 3400)));
293 
294             NetworkCapabilities netCap2 = new NetworkCapabilities();
295             // A new netcap object has null UIDs, so anything will satisfy it.
296             assertTrue(netCap2.satisfiedByUids(netCap));
297             // Still not equal though.
298             assertFalse(netCap2.equalsUids(netCap));
299             netCap2.setUids(uids);
300             assertTrue(netCap2.satisfiedByUids(netCap));
301             assertTrue(netCap.equalsUids(netCap2));
302             assertTrue(netCap2.equalsUids(netCap));
303 
304             uids.add(uidRange(600, 700));
305             netCap2.setUids(uids);
306             assertFalse(netCap2.satisfiedByUids(netCap));
307             assertFalse(netCap.appliesToUid(650));
308             assertTrue(netCap2.appliesToUid(650));
309             netCap.setUids(uids);
310             assertTrue(netCap2.satisfiedByUids(netCap));
311             assertTrue(netCap.appliesToUid(650));
312             assertFalse(netCap.appliesToUid(500));
313 
314             // Null uids satisfies everything.
315             netCap.setUids(null);
316             assertTrue(netCap2.satisfiedByUids(netCap));
317             assertTrue(netCap.satisfiedByUids(netCap2));
318             netCap2.setUids(null);
319             assertTrue(netCap2.satisfiedByUids(netCap));
320             assertTrue(netCap.satisfiedByUids(netCap2));
321         }
322     }
323 
324     @Test @IgnoreUpTo(SC_V2)
testSetAllowedUids()325     public void testSetAllowedUids() {
326         final NetworkCapabilities nc = new NetworkCapabilities();
327         assertThrows(NullPointerException.class, () -> nc.setAllowedUids(null));
328         assertFalse(nc.hasAllowedUids());
329         assertFalse(nc.isUidWithAccess(0));
330         assertFalse(nc.isUidWithAccess(1000));
331         assertEquals(0, nc.getAllowedUids().size());
332         nc.setAllowedUids(new ArraySet<>());
333         assertFalse(nc.hasAllowedUids());
334         assertFalse(nc.isUidWithAccess(0));
335         assertFalse(nc.isUidWithAccess(1000));
336         assertEquals(0, nc.getAllowedUids().size());
337 
338         final ArraySet<Integer> uids = new ArraySet<>();
339         uids.add(200);
340         uids.add(250);
341         uids.add(-1);
342         uids.add(Integer.MAX_VALUE);
343         nc.setAllowedUids(uids);
344         assertNotEquals(nc, new NetworkCapabilities());
345         assertTrue(nc.hasAllowedUids());
346 
347         final List<Integer> includedList = List.of(-2, 0, 199, 700, 901, 1000, Integer.MIN_VALUE);
348         final List<Integer> excludedList = List.of(-1, 200, 250, Integer.MAX_VALUE);
349         for (final int uid : includedList) {
350             assertFalse(nc.isUidWithAccess(uid));
351         }
352         for (final int uid : excludedList) {
353             assertTrue(nc.isUidWithAccess(uid));
354         }
355 
356         final Set<Integer> outUids = nc.getAllowedUids();
357         assertEquals(4, outUids.size());
358         for (final int uid : includedList) {
359             assertFalse(outUids.contains(uid));
360         }
361         for (final int uid : excludedList) {
362             assertTrue(outUids.contains(uid));
363         }
364     }
365 
366     @Test
testParcelNetworkCapabilities()367     public void testParcelNetworkCapabilities() {
368         final Set<Range<Integer>> uids = new ArraySet<>();
369         uids.add(uidRange(50, 100));
370         uids.add(uidRange(3000, 4000));
371         final NetworkCapabilities netCap = new NetworkCapabilities()
372             .addCapability(NET_CAPABILITY_INTERNET)
373             .addCapability(NET_CAPABILITY_EIMS)
374             .addCapability(NET_CAPABILITY_NOT_METERED);
375         if (isAtLeastV()) {
376             netCap.addCapability(NET_CAPABILITY_LOCAL_NETWORK);
377         }
378         if (isAtLeastS()) {
379             final ArraySet<Integer> allowedUids = new ArraySet<>();
380             allowedUids.add(4);
381             allowedUids.add(9);
382             netCap.setAllowedUids(allowedUids);
383             netCap.setSubscriptionIds(Set.of(TEST_SUBID1, TEST_SUBID2));
384             netCap.setUids(uids);
385         }
386 
387         netCap.setOwnerUid(123);
388         netCap.setAdministratorUids(new int[] {5, 11});
389         assertParcelingIsLossless(netCap);
390         netCap.setSSID(TEST_SSID);
391         testParcelSane(netCap);
392     }
393 
394     @Test
testParcelNetworkCapabilitiesWithRequestorUidAndPackageName()395     public void testParcelNetworkCapabilitiesWithRequestorUidAndPackageName() {
396         final NetworkCapabilities netCap = new NetworkCapabilities()
397                 .addCapability(NET_CAPABILITY_INTERNET)
398                 .addCapability(NET_CAPABILITY_EIMS)
399                 .addCapability(NET_CAPABILITY_NOT_METERED);
400         netCap.setRequestorPackageName("com.android.test");
401         netCap.setRequestorUid(9304);
402         assertParcelingIsLossless(netCap);
403         netCap.setSSID(TEST_SSID);
404         testParcelSane(netCap);
405     }
406 
testParcelSane(NetworkCapabilities cap)407     private void testParcelSane(NetworkCapabilities cap) {
408         assertParcelingIsLossless(cap);
409     }
410 
createNetworkCapabilitiesWithTransportInfo()411     private static NetworkCapabilities createNetworkCapabilitiesWithTransportInfo() {
412         return new NetworkCapabilities()
413                 .addCapability(NET_CAPABILITY_INTERNET)
414                 .addCapability(NET_CAPABILITY_EIMS)
415                 .addCapability(NET_CAPABILITY_NOT_METERED)
416                 .setSSID(TEST_SSID)
417                 .setTransportInfo(new TestTransportInfo())
418                 .setRequestorPackageName("com.android.test")
419                 .setRequestorUid(9304);
420     }
421 
422     @Test
testNetworkCapabilitiesCopyWithNoRedactions()423     public void testNetworkCapabilitiesCopyWithNoRedactions() {
424         assumeTrue(isAtLeastS());
425 
426         final NetworkCapabilities netCap = createNetworkCapabilitiesWithTransportInfo();
427         final NetworkCapabilities netCapWithNoRedactions =
428                 new NetworkCapabilities(netCap, NetworkCapabilities.REDACT_NONE);
429         TestTransportInfo testTransportInfo =
430                 (TestTransportInfo) netCapWithNoRedactions.getTransportInfo();
431         assertFalse(testTransportInfo.locationRedacted);
432         assertFalse(testTransportInfo.localMacAddressRedacted);
433         assertFalse(testTransportInfo.settingsRedacted);
434     }
435 
436     @Test
testNetworkCapabilitiesCopyWithoutLocationSensitiveFields()437     public void testNetworkCapabilitiesCopyWithoutLocationSensitiveFields() {
438         assumeTrue(isAtLeastS());
439 
440         final NetworkCapabilities netCap = createNetworkCapabilitiesWithTransportInfo();
441         final NetworkCapabilities netCapWithNoRedactions =
442                 new NetworkCapabilities(netCap, REDACT_FOR_ACCESS_FINE_LOCATION);
443         TestTransportInfo testTransportInfo =
444                 (TestTransportInfo) netCapWithNoRedactions.getTransportInfo();
445         assertTrue(testTransportInfo.locationRedacted);
446         assertFalse(testTransportInfo.localMacAddressRedacted);
447         assertFalse(testTransportInfo.settingsRedacted);
448     }
449 
450     @Test
testOemPaid()451     public void testOemPaid() {
452         NetworkCapabilities nc = new NetworkCapabilities();
453         // By default OEM_PAID is neither in the required or forbidden lists and the network is not
454         // restricted.
455         if (isAtLeastS()) {
456             assertFalse(nc.hasForbiddenCapability(NET_CAPABILITY_OEM_PAID));
457         }
458         assertFalse(nc.hasCapability(NET_CAPABILITY_OEM_PAID));
459         nc.maybeMarkCapabilitiesRestricted();
460         assertTrue(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
461 
462         // Adding OEM_PAID to capability list should make network restricted.
463         nc.addCapability(NET_CAPABILITY_OEM_PAID);
464         nc.addCapability(NET_CAPABILITY_INTERNET);  // Combine with unrestricted capability.
465         nc.maybeMarkCapabilitiesRestricted();
466         assertTrue(nc.hasCapability(NET_CAPABILITY_OEM_PAID));
467         assertFalse(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
468 
469         // Now let's make request for OEM_PAID network.
470         NetworkCapabilities nr = new NetworkCapabilities();
471         nr.addCapability(NET_CAPABILITY_OEM_PAID);
472         nr.maybeMarkCapabilitiesRestricted();
473         assertTrue(nr.satisfiedByNetworkCapabilities(nc));
474 
475         // Request fails for network with the default capabilities.
476         assertFalse(nr.satisfiedByNetworkCapabilities(new NetworkCapabilities()));
477     }
478 
479     @Test @IgnoreUpTo(SC_V2) // TODO: Use to Build.VERSION_CODES.SC_V2 when available
testPrioritizeLatencyAndBandwidth()480     public void testPrioritizeLatencyAndBandwidth() {
481         NetworkCapabilities netCap = new NetworkCapabilities();
482         netCap.addCapability(NET_CAPABILITY_PRIORITIZE_LATENCY);
483         netCap.addCapability(NET_CAPABILITY_NOT_METERED);
484         netCap.maybeMarkCapabilitiesRestricted();
485         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
486         netCap = new NetworkCapabilities();
487         netCap.addCapability(NET_CAPABILITY_PRIORITIZE_LATENCY);
488         netCap.removeCapability(NET_CAPABILITY_NOT_METERED);
489         netCap.maybeMarkCapabilitiesRestricted();
490         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
491 
492         netCap = new NetworkCapabilities();
493         netCap.addCapability(NET_CAPABILITY_PRIORITIZE_BANDWIDTH);
494         netCap.addCapability(NET_CAPABILITY_NOT_METERED);
495         netCap.maybeMarkCapabilitiesRestricted();
496         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
497         netCap = new NetworkCapabilities();
498         netCap.addCapability(NET_CAPABILITY_PRIORITIZE_BANDWIDTH);
499         netCap.removeCapability(NET_CAPABILITY_NOT_METERED);
500         netCap.maybeMarkCapabilitiesRestricted();
501         assertTrue(netCap.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
502     }
503 
504     @Test
testOemPrivate()505     public void testOemPrivate() {
506         NetworkCapabilities nc = new NetworkCapabilities();
507         // By default OEM_PRIVATE is neither in the required or forbidden lists and the network is
508         // not restricted.
509         assertFalse(nc.hasForbiddenCapability(NET_CAPABILITY_OEM_PRIVATE));
510         assertFalse(nc.hasCapability(NET_CAPABILITY_OEM_PRIVATE));
511         nc.maybeMarkCapabilitiesRestricted();
512         assertTrue(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
513 
514         // Adding OEM_PRIVATE to capability list should make network restricted.
515         nc.addCapability(NET_CAPABILITY_OEM_PRIVATE);
516         nc.addCapability(NET_CAPABILITY_INTERNET);  // Combine with unrestricted capability.
517         nc.maybeMarkCapabilitiesRestricted();
518         assertTrue(nc.hasCapability(NET_CAPABILITY_OEM_PRIVATE));
519         assertFalse(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
520 
521         // Now let's make request for OEM_PRIVATE network.
522         NetworkCapabilities nr = new NetworkCapabilities();
523         nr.addCapability(NET_CAPABILITY_OEM_PRIVATE);
524         nr.maybeMarkCapabilitiesRestricted();
525         assertTrue(nr.satisfiedByNetworkCapabilities(nc));
526 
527         // Request fails for network with the default capabilities.
528         assertFalse(nr.satisfiedByNetworkCapabilities(new NetworkCapabilities()));
529     }
530 
531     @Test
testForbiddenCapabilities()532     public void testForbiddenCapabilities() {
533         NetworkCapabilities network = new NetworkCapabilities();
534 
535         NetworkCapabilities request = new NetworkCapabilities();
536         assertTrue("Request: " + request + ", Network:" + network,
537                 request.satisfiedByNetworkCapabilities(network));
538 
539         // Requesting absence of capabilities that network doesn't have. Request should satisfy.
540         request.addForbiddenCapability(NET_CAPABILITY_WIFI_P2P);
541         request.addForbiddenCapability(NET_CAPABILITY_NOT_METERED);
542         assertTrue(request.satisfiedByNetworkCapabilities(network));
543         assertArrayEquals(new int[]{NET_CAPABILITY_WIFI_P2P,
544                         NET_CAPABILITY_NOT_METERED},
545                 request.getForbiddenCapabilities());
546 
547         // This is a default capability, just want to make sure its there because we use it below.
548         assertTrue(network.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
549 
550         // Verify that adding forbidden capability will effectively remove it from capability list.
551         request.addForbiddenCapability(NET_CAPABILITY_NOT_RESTRICTED);
552         assertTrue(request.hasForbiddenCapability(NET_CAPABILITY_NOT_RESTRICTED));
553         assertFalse(request.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
554 
555         // Now this request won't be satisfied because network contains NOT_RESTRICTED.
556         assertFalse(request.satisfiedByNetworkCapabilities(network));
557         network.removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
558         assertTrue(request.satisfiedByNetworkCapabilities(network));
559 
560         // Verify that adding capability will effectively remove it from forbidden list
561         request.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
562         assertTrue(request.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
563         assertFalse(request.hasForbiddenCapability(NET_CAPABILITY_NOT_RESTRICTED));
564 
565         assertFalse(request.satisfiedByNetworkCapabilities(network));
566         network.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
567         assertTrue(request.satisfiedByNetworkCapabilities(network));
568     }
569 
570     @Test
testConnectivityManagedCapabilities()571     public void testConnectivityManagedCapabilities() {
572         NetworkCapabilities nc = new NetworkCapabilities();
573         assertFalse(nc.hasConnectivityManagedCapability());
574         // Check every single system managed capability.
575         nc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
576         assertTrue(nc.hasConnectivityManagedCapability());
577         nc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
578         nc.addCapability(NET_CAPABILITY_FOREGROUND);
579         assertTrue(nc.hasConnectivityManagedCapability());
580         nc.removeCapability(NET_CAPABILITY_FOREGROUND);
581         nc.addCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
582         assertTrue(nc.hasConnectivityManagedCapability());
583         nc.removeCapability(NET_CAPABILITY_PARTIAL_CONNECTIVITY);
584         nc.addCapability(NET_CAPABILITY_VALIDATED);
585         assertTrue(nc.hasConnectivityManagedCapability());
586     }
587 
588     @Test
testEqualsNetCapabilities()589     public void testEqualsNetCapabilities() {
590         NetworkCapabilities nc1 = new NetworkCapabilities();
591         NetworkCapabilities nc2 = new NetworkCapabilities();
592         assertTrue(nc1.equalsNetCapabilities(nc2));
593         assertEquals(nc1, nc2);
594 
595         nc1.addCapability(NET_CAPABILITY_MMS);
596         assertFalse(nc1.equalsNetCapabilities(nc2));
597         assertNotEquals(nc1, nc2);
598         nc2.addCapability(NET_CAPABILITY_MMS);
599         assertTrue(nc1.equalsNetCapabilities(nc2));
600         assertEquals(nc1, nc2);
601 
602         if (isAtLeastS()) {
603             nc1.addForbiddenCapability(NET_CAPABILITY_INTERNET);
604             assertFalse(nc1.equalsNetCapabilities(nc2));
605             nc2.addForbiddenCapability(NET_CAPABILITY_INTERNET);
606             assertTrue(nc1.equalsNetCapabilities(nc2));
607 
608             // Remove a required capability doesn't affect forbidden capabilities.
609             // This is a behaviour change from R to S.
610             nc1.removeCapability(NET_CAPABILITY_INTERNET);
611             assertTrue(nc1.equalsNetCapabilities(nc2));
612 
613             nc1.removeForbiddenCapability(NET_CAPABILITY_INTERNET);
614             assertFalse(nc1.equalsNetCapabilities(nc2));
615             nc2.removeForbiddenCapability(NET_CAPABILITY_INTERNET);
616             assertTrue(nc1.equalsNetCapabilities(nc2));
617         }
618     }
619 
620     @Test
testSSID()621     public void testSSID() {
622         NetworkCapabilities nc1 = new NetworkCapabilities();
623         NetworkCapabilities nc2 = new NetworkCapabilities();
624         assertTrue(nc2.satisfiedBySSID(nc1));
625 
626         nc1.setSSID(TEST_SSID);
627         assertTrue(nc2.satisfiedBySSID(nc1));
628         nc2.setSSID("different " + TEST_SSID);
629         assertFalse(nc2.satisfiedBySSID(nc1));
630 
631         assertTrue(nc1.satisfiedByImmutableNetworkCapabilities(nc2));
632         assertFalse(nc1.satisfiedByNetworkCapabilities(nc2));
633     }
634 
uidRanges(int from, int to)635     private ArraySet<Range<Integer>> uidRanges(int from, int to) {
636         final ArraySet<Range<Integer>> range = new ArraySet<>(1);
637         range.add(uidRange(from, to));
638         return range;
639     }
640 
uidRange(int from, int to)641     private Range<Integer> uidRange(int from, int to) {
642         return new Range<Integer>(from, to);
643     }
644 
645     @Test
testSetAdministratorUids()646     public void testSetAdministratorUids() {
647         NetworkCapabilities nc =
648                 new NetworkCapabilities().setAdministratorUids(new int[] {2, 1, 3});
649 
650         assertArrayEquals(new int[] {1, 2, 3}, nc.getAdministratorUids());
651     }
652 
653     @Test
testSetAdministratorUidsWithDuplicates()654     public void testSetAdministratorUidsWithDuplicates() {
655         try {
656             new NetworkCapabilities().setAdministratorUids(new int[] {1, 1});
657             fail("Expected IllegalArgumentException for duplicate uids");
658         } catch (IllegalArgumentException expected) {
659         }
660     }
661 
662     @Test
testSetCapabilities()663     public void testSetCapabilities() {
664         final int[] REQUIRED_CAPABILITIES = new int[] {
665                 NET_CAPABILITY_INTERNET, NET_CAPABILITY_NOT_VPN };
666 
667         NetworkCapabilities nc1 = new NetworkCapabilities();
668         NetworkCapabilities nc2 = new NetworkCapabilities();
669 
670         nc1.setCapabilities(REQUIRED_CAPABILITIES);
671         assertArrayEquals(REQUIRED_CAPABILITIES, nc1.getCapabilities());
672 
673         // Verify that setting and adding capabilities leads to the same object state.
674         nc2.clearAll();
675         for (int cap : REQUIRED_CAPABILITIES) {
676             nc2.addCapability(cap);
677         }
678         assertEquals(nc1, nc2);
679 
680         if (isAtLeastS()) {
681             final int[] forbiddenCapabilities = new int[]{
682                     NET_CAPABILITY_NOT_METERED, NET_CAPABILITY_NOT_RESTRICTED };
683 
684             nc1.setCapabilities(REQUIRED_CAPABILITIES, forbiddenCapabilities);
685             assertArrayEquals(REQUIRED_CAPABILITIES, nc1.getCapabilities());
686             assertArrayEquals(forbiddenCapabilities, nc1.getForbiddenCapabilities());
687 
688             nc2.clearAll();
689             for (int cap : REQUIRED_CAPABILITIES) {
690                 nc2.addCapability(cap);
691             }
692             for (int cap : forbiddenCapabilities) {
693                 nc2.addForbiddenCapability(cap);
694             }
695             assertEquals(nc1, nc2);
696         }
697     }
698 
699     @Test
testUnderlyingNetworks()700     public void testUnderlyingNetworks() {
701         assumeTrue(isAtLeastT());
702         final NetworkCapabilities nc = new NetworkCapabilities();
703         final Network network1 = new Network(100);
704         final Network network2 = new Network(101);
705         final ArrayList<Network> inputNetworks = new ArrayList<>();
706         inputNetworks.add(network1);
707         inputNetworks.add(network2);
708         nc.setUnderlyingNetworks(inputNetworks);
709         final ArrayList<Network> outputNetworks = new ArrayList<>(nc.getUnderlyingNetworks());
710         assertEquals(network1, outputNetworks.get(0));
711         assertEquals(network2, outputNetworks.get(1));
712         nc.setUnderlyingNetworks(null);
713         assertNull(nc.getUnderlyingNetworks());
714     }
715 
716     @Test
testEqualsForUnderlyingNetworks()717     public void testEqualsForUnderlyingNetworks() {
718         assumeTrue(isAtLeastT());
719         final NetworkCapabilities nc1 = new NetworkCapabilities();
720         final NetworkCapabilities nc2 = new NetworkCapabilities();
721         assertEquals(nc1, nc2);
722         final Network network = new Network(100);
723         final ArrayList<Network> inputNetworks = new ArrayList<>();
724         final ArrayList<Network> emptyList = new ArrayList<>();
725         inputNetworks.add(network);
726         nc1.setUnderlyingNetworks(inputNetworks);
727         assertNotEquals(nc1, nc2);
728         nc2.setUnderlyingNetworks(inputNetworks);
729         assertEquals(nc1, nc2);
730         nc1.setUnderlyingNetworks(emptyList);
731         assertNotEquals(nc1, nc2);
732         nc2.setUnderlyingNetworks(emptyList);
733         assertEquals(nc1, nc2);
734         nc1.setUnderlyingNetworks(null);
735         assertNotEquals(nc1, nc2);
736         nc2.setUnderlyingNetworks(null);
737         assertEquals(nc1, nc2);
738     }
739 
740     @Test
testSetNetworkSpecifierOnMultiTransportNc()741     public void testSetNetworkSpecifierOnMultiTransportNc() {
742         // Sequence 1: Transport + Transport + NetworkSpecifier
743         NetworkCapabilities.Builder nc1 = new NetworkCapabilities.Builder();
744         nc1.addTransportType(TRANSPORT_CELLULAR).addTransportType(TRANSPORT_WIFI);
745         final NetworkSpecifier specifier = CompatUtil.makeEthernetNetworkSpecifier("eth0");
746         assertThrows("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!",
747                 IllegalStateException.class,
748                 () -> nc1.build().setNetworkSpecifier(specifier));
749         assertThrows("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!",
750                 IllegalStateException.class,
751                 () -> nc1.setNetworkSpecifier(specifier));
752 
753         // Sequence 2: Transport + NetworkSpecifier + Transport
754         NetworkCapabilities.Builder nc2 = new NetworkCapabilities.Builder();
755         nc2.addTransportType(TRANSPORT_CELLULAR).setNetworkSpecifier(specifier);
756 
757         assertThrows("Cannot set a second TransportType of a network which has a NetworkSpecifier!",
758                 IllegalStateException.class,
759                 () -> nc2.build().addTransportType(TRANSPORT_WIFI));
760         assertThrows("Cannot set a second TransportType of a network which has a NetworkSpecifier!",
761                 IllegalStateException.class,
762                 () -> nc2.addTransportType(TRANSPORT_WIFI));
763     }
764 
765     @Test
testSetNetworkSpecifierWithCellularAndSatelliteMultiTransportNc()766     public void testSetNetworkSpecifierWithCellularAndSatelliteMultiTransportNc() {
767         final TelephonyNetworkSpecifier specifier = new TelephonyNetworkSpecifier(1);
768         NetworkCapabilities nc = new NetworkCapabilities.Builder()
769                 .addTransportType(TRANSPORT_CELLULAR)
770                 .addTransportType(TRANSPORT_SATELLITE)
771                 .setNetworkSpecifier(specifier)
772                 .build();
773         // Adding a specifier did not crash with 2 transports if it is cellular + satellite
774         assertEquals(specifier, nc.getNetworkSpecifier());
775     }
776 
777     @Test
testSetNetworkSpecifierWithWifiAndSatelliteMultiTransportNc()778     public void testSetNetworkSpecifierWithWifiAndSatelliteMultiTransportNc() {
779         final TelephonyNetworkSpecifier specifier = new TelephonyNetworkSpecifier(1);
780         NetworkCapabilities.Builder nc1 = new NetworkCapabilities.Builder();
781         nc1.addTransportType(TRANSPORT_SATELLITE).addTransportType(TRANSPORT_WIFI);
782         // Adding multiple transports specifier to crash, apart from cellular + satellite
783         // combination
784         assertThrows("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!",
785                 IllegalStateException.class,
786                 () -> nc1.build().setNetworkSpecifier(specifier));
787         assertThrows("Cannot set NetworkSpecifier on a NetworkCapability with multiple transports!",
788                 IllegalStateException.class,
789                 () -> nc1.setNetworkSpecifier(specifier));
790     }
791 
792     @Test
testSetNetworkSpecifierOnTestWithCellularAndSatelliteMultiTransportNc()793     public void testSetNetworkSpecifierOnTestWithCellularAndSatelliteMultiTransportNc() {
794         final TelephonyNetworkSpecifier specifier = new TelephonyNetworkSpecifier(1);
795         NetworkCapabilities nc = new NetworkCapabilities.Builder()
796                 .addTransportType(TRANSPORT_TEST)
797                 .addTransportType(TRANSPORT_CELLULAR)
798                 .addTransportType(TRANSPORT_SATELLITE)
799                 .setNetworkSpecifier(specifier)
800                 .build();
801         // Adding a specifier did not crash with 3 transports , TEST + CELLULAR + SATELLITE and if
802         // one is test
803         assertEquals(specifier, nc.getNetworkSpecifier());
804     }
805 
806     @Test
testSetNetworkSpecifierOnTestMultiTransportNc()807     public void testSetNetworkSpecifierOnTestMultiTransportNc() {
808         final NetworkSpecifier specifier = CompatUtil.makeEthernetNetworkSpecifier("eth0");
809         NetworkCapabilities nc = new NetworkCapabilities.Builder()
810                 .addTransportType(TRANSPORT_TEST)
811                 .addTransportType(TRANSPORT_ETHERNET)
812                 .setNetworkSpecifier(specifier)
813                 .build();
814         // Adding a specifier did not crash with 2 transports if one is TEST
815         assertEquals(specifier, nc.getNetworkSpecifier());
816     }
817 
818     @Test
testSetTransportInfoOnMultiTransportNc()819     public void testSetTransportInfoOnMultiTransportNc() {
820         // Sequence 1: Transport + Transport + TransportInfo
821         NetworkCapabilities nc1 = new NetworkCapabilities();
822         nc1.addTransportType(TRANSPORT_CELLULAR).addTransportType(TRANSPORT_WIFI)
823                 .setTransportInfo(new TestTransportInfo());
824 
825         // Sequence 2: Transport + NetworkSpecifier + Transport
826         NetworkCapabilities nc2 = new NetworkCapabilities();
827         nc2.addTransportType(TRANSPORT_CELLULAR).setTransportInfo(new TestTransportInfo())
828                 .addTransportType(TRANSPORT_WIFI);
829     }
830 
831     @Test
testSet()832     public void testSet() {
833         NetworkCapabilities nc1 = new NetworkCapabilities();
834         NetworkCapabilities nc2 = new NetworkCapabilities();
835 
836         if (isAtLeastS()) {
837             nc1.addForbiddenCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
838         }
839         nc1.addCapability(NET_CAPABILITY_NOT_ROAMING);
840         assertNotEquals(nc1, nc2);
841         nc2.set(nc1);
842         assertEquals(nc1, nc2);
843         assertTrue(nc2.hasCapability(NET_CAPABILITY_NOT_ROAMING));
844         if (isAtLeastS()) {
845             assertTrue(nc2.hasForbiddenCapability(NET_CAPABILITY_CAPTIVE_PORTAL));
846         }
847 
848         if (isAtLeastS()) {
849             // This will effectively move NOT_ROAMING capability from required to forbidden for nc1.
850             nc1.addForbiddenCapability(NET_CAPABILITY_NOT_ROAMING);
851         }
852         nc1.setSSID(TEST_SSID);
853         nc2.set(nc1);
854         assertEquals(nc1, nc2);
855         if (isAtLeastS()) {
856             // Contrary to combineCapabilities, set() will have removed the NOT_ROAMING capability
857             // from nc2.
858             assertFalse(nc2.hasCapability(NET_CAPABILITY_NOT_ROAMING));
859             assertTrue(nc2.hasForbiddenCapability(NET_CAPABILITY_NOT_ROAMING));
860         }
861 
862         assertTrue(TEST_SSID.equals(nc2.getSsid()));
863         nc1.setSSID(DIFFERENT_TEST_SSID);
864         nc2.set(nc1);
865         assertEquals(nc1, nc2);
866         assertTrue(DIFFERENT_TEST_SSID.equals(nc2.getSsid()));
867 
868         if (isAtLeastS()) {
869             nc1.setUids(uidRanges(10, 13));
870         } else {
871             nc1.setUids(null);
872         }
873         nc2.set(nc1);  // Overwrites, as opposed to combineCapabilities
874         assertEquals(nc1, nc2);
875 
876         if (isAtLeastS()) {
877             assertThrows(NullPointerException.class, () -> nc1.setSubscriptionIds(null));
878             nc1.setSubscriptionIds(Set.of());
879             nc2.set(nc1);
880             assertEquals(nc1, nc2);
881 
882             nc1.setSubscriptionIds(Set.of(TEST_SUBID1));
883             nc2.set(nc1);
884             assertEquals(nc1, nc2);
885 
886             nc2.setSubscriptionIds(Set.of(TEST_SUBID2, TEST_SUBID1));
887             nc2.set(nc1);
888             assertEquals(nc1, nc2);
889 
890             nc2.setSubscriptionIds(Set.of(TEST_SUBID3, TEST_SUBID2));
891             assertNotEquals(nc1, nc2);
892         }
893     }
894 
895     @Test
testGetTransportTypes()896     public void testGetTransportTypes() {
897         final NetworkCapabilities nc = new NetworkCapabilities();
898         nc.addTransportType(TRANSPORT_CELLULAR);
899         nc.addTransportType(TRANSPORT_WIFI);
900         nc.addTransportType(TRANSPORT_VPN);
901         nc.addTransportType(TRANSPORT_TEST);
902 
903         final int[] transportTypes = nc.getTransportTypes();
904         assertEquals(4, transportTypes.length);
905         assertEquals(TRANSPORT_CELLULAR, transportTypes[0]);
906         assertEquals(TRANSPORT_WIFI, transportTypes[1]);
907         assertEquals(TRANSPORT_VPN, transportTypes[2]);
908         assertEquals(TRANSPORT_TEST, transportTypes[3]);
909     }
910 
911     @Test
testTelephonyNetworkSpecifier()912     public void testTelephonyNetworkSpecifier() {
913         final TelephonyNetworkSpecifier specifier = new TelephonyNetworkSpecifier(1);
914         final NetworkCapabilities nc1 = new NetworkCapabilities.Builder()
915                 .addTransportType(TRANSPORT_WIFI)
916                 .setNetworkSpecifier(specifier)
917                 .build();
918         assertEquals(specifier, nc1.getNetworkSpecifier());
919         try {
920             final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
921                     .setNetworkSpecifier(specifier)
922                     .build();
923             fail("Must have a single transport type. Without transport type or multiple transport"
924                     + " types is invalid.");
925         } catch (IllegalStateException expected) { }
926     }
927 
928     @Test @IgnoreUpTo(SC_V2) // TODO: Use to Build.VERSION_CODES.SC_V2 when available
testEnterpriseId()929     public void testEnterpriseId() {
930         final NetworkCapabilities nc1 = new NetworkCapabilities.Builder()
931                 .addCapability(NET_CAPABILITY_ENTERPRISE)
932                 .addEnterpriseId(NET_ENTERPRISE_ID_1)
933                 .build();
934         assertEquals(1, nc1.getEnterpriseIds().length);
935         assertEquals(NET_ENTERPRISE_ID_1,
936                 nc1.getEnterpriseIds()[0]);
937         final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
938                 .addCapability(NET_CAPABILITY_ENTERPRISE)
939                 .addEnterpriseId(NET_ENTERPRISE_ID_1)
940                 .addEnterpriseId(NET_ENTERPRISE_ID_2)
941                 .build();
942         assertEquals(2, nc2.getEnterpriseIds().length);
943         assertEquals(NET_ENTERPRISE_ID_1,
944                 nc2.getEnterpriseIds()[0]);
945         assertEquals(NET_ENTERPRISE_ID_2,
946                 nc2.getEnterpriseIds()[1]);
947         final NetworkCapabilities nc3 = new NetworkCapabilities.Builder()
948                 .addCapability(NET_CAPABILITY_ENTERPRISE)
949                 .addEnterpriseId(NET_ENTERPRISE_ID_1)
950                 .addEnterpriseId(NET_ENTERPRISE_ID_2)
951                 .addEnterpriseId(NET_ENTERPRISE_ID_3)
952                 .addEnterpriseId(NET_ENTERPRISE_ID_4)
953                 .addEnterpriseId(NET_ENTERPRISE_ID_5)
954                 .build();
955         assertEquals(5, nc3.getEnterpriseIds().length);
956         assertEquals(NET_ENTERPRISE_ID_1,
957                 nc3.getEnterpriseIds()[0]);
958         assertEquals(NET_ENTERPRISE_ID_2,
959                 nc3.getEnterpriseIds()[1]);
960         assertEquals(NET_ENTERPRISE_ID_3,
961                 nc3.getEnterpriseIds()[2]);
962         assertEquals(NET_ENTERPRISE_ID_4,
963                 nc3.getEnterpriseIds()[3]);
964         assertEquals(NET_ENTERPRISE_ID_5,
965                 nc3.getEnterpriseIds()[4]);
966 
967         final Class<IllegalArgumentException> illegalArgumentExceptionClass =
968                 IllegalArgumentException.class;
969         assertThrows(illegalArgumentExceptionClass, () -> new NetworkCapabilities.Builder()
970                 .addEnterpriseId(6)
971                 .build());
972         assertThrows(illegalArgumentExceptionClass, () -> new NetworkCapabilities.Builder()
973                 .removeEnterpriseId(6)
974                 .build());
975 
976         final Class<IllegalStateException> illegalStateException =
977                 IllegalStateException.class;
978         assertThrows(illegalStateException, () -> new NetworkCapabilities.Builder()
979                 .addEnterpriseId(NET_ENTERPRISE_ID_1)
980                 .build());
981 
982         final NetworkCapabilities nc4 = new NetworkCapabilities.Builder()
983                 .addCapability(NET_CAPABILITY_ENTERPRISE)
984                 .addEnterpriseId(NET_ENTERPRISE_ID_1)
985                 .addEnterpriseId(NET_ENTERPRISE_ID_2)
986                 .removeEnterpriseId(NET_ENTERPRISE_ID_1)
987                 .removeEnterpriseId(NET_ENTERPRISE_ID_2)
988                 .build();
989         assertEquals(1, nc4.getEnterpriseIds().length);
990         assertTrue(nc4.hasEnterpriseId(NET_ENTERPRISE_ID_1));
991 
992         final NetworkCapabilities nc5 = new NetworkCapabilities.Builder()
993                 .addCapability(NET_CAPABILITY_CBS)
994                 .addEnterpriseId(NET_ENTERPRISE_ID_1)
995                 .addEnterpriseId(NET_ENTERPRISE_ID_2)
996                 .removeEnterpriseId(NET_ENTERPRISE_ID_1)
997                 .removeEnterpriseId(NET_ENTERPRISE_ID_2)
998                 .build();
999 
1000         assertTrue(nc4.satisfiedByNetworkCapabilities(nc1));
1001         assertTrue(nc1.satisfiedByNetworkCapabilities(nc4));
1002 
1003         assertFalse(nc3.satisfiedByNetworkCapabilities(nc2));
1004         assertTrue(nc2.satisfiedByNetworkCapabilities(nc3));
1005 
1006         assertFalse(nc1.satisfiedByNetworkCapabilities(nc5));
1007         assertFalse(nc5.satisfiedByNetworkCapabilities(nc1));
1008     }
1009 
1010     @Test
testWifiAwareNetworkSpecifier()1011     public void testWifiAwareNetworkSpecifier() {
1012         final NetworkCapabilities nc = new NetworkCapabilities()
1013                 .addTransportType(TRANSPORT_WIFI_AWARE);
1014         // If NetworkSpecifier is not set, the default value is null.
1015         assertNull(nc.getNetworkSpecifier());
1016         final WifiAwareNetworkSpecifier specifier = new WifiAwareNetworkSpecifier.Builder(
1017                 mDiscoverySession, mPeerHandle).build();
1018         nc.setNetworkSpecifier(specifier);
1019         assertEquals(specifier, nc.getNetworkSpecifier());
1020     }
1021 
1022     @Test
testAdministratorUidsAndOwnerUid()1023     public void testAdministratorUidsAndOwnerUid() {
1024         // Test default owner uid.
1025         // If the owner uid is not set, the default value should be Process.INVALID_UID.
1026         final NetworkCapabilities nc1 = new NetworkCapabilities.Builder().build();
1027         assertEquals(INVALID_UID, nc1.getOwnerUid());
1028         // Test setAdministratorUids and getAdministratorUids.
1029         final int[] administratorUids = {1001, 10001};
1030         final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
1031                 .setAdministratorUids(administratorUids)
1032                 .build();
1033         assertTrue(Arrays.equals(administratorUids, nc2.getAdministratorUids()));
1034         // Test setOwnerUid and getOwnerUid.
1035         // The owner UID must be included in administrator UIDs, or throw IllegalStateException.
1036         try {
1037             final NetworkCapabilities nc3 = new NetworkCapabilities.Builder()
1038                     .setOwnerUid(1001)
1039                     .build();
1040             fail("The owner UID must be included in administrator UIDs.");
1041         } catch (IllegalStateException expected) { }
1042         final NetworkCapabilities nc4 = new NetworkCapabilities.Builder()
1043                 .setAdministratorUids(administratorUids)
1044                 .setOwnerUid(1001)
1045                 .build();
1046         assertEquals(1001, nc4.getOwnerUid());
1047         try {
1048             final NetworkCapabilities nc5 = new NetworkCapabilities.Builder()
1049                     .setAdministratorUids(null)
1050                     .build();
1051             fail("Should not set null into setAdministratorUids");
1052         } catch (NullPointerException expected) { }
1053     }
1054 
capsWithSubIds(Integer .... subIds)1055     private static NetworkCapabilities capsWithSubIds(Integer ... subIds) {
1056         // Since the NetworkRequest would put NOT_VCN_MANAGED capabilities in general, for
1057         // every NetworkCapabilities that simulates networks needs to add it too in order to
1058         // satisfy these requests.
1059         final NetworkCapabilities nc = new NetworkCapabilities.Builder()
1060                 .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED)
1061                 .setSubscriptionIds(new ArraySet<>(subIds)).build();
1062         assertEquals(new ArraySet<>(subIds), nc.getSubscriptionIds());
1063         return nc;
1064     }
1065 
1066     @Test
testSubIds()1067     public void testSubIds() throws Exception {
1068         final NetworkCapabilities ncWithoutId = capsWithSubIds();
1069         final NetworkCapabilities ncWithId = capsWithSubIds(TEST_SUBID1);
1070         final NetworkCapabilities ncWithOtherIds = capsWithSubIds(TEST_SUBID1, TEST_SUBID3);
1071         final NetworkCapabilities ncWithoutRequestedIds = capsWithSubIds(TEST_SUBID3);
1072 
1073         final NetworkRequest requestWithoutId = new NetworkRequest.Builder().build();
1074         assertEmpty(requestWithoutId.networkCapabilities.getSubscriptionIds());
1075         final NetworkRequest requestWithIds = new NetworkRequest.Builder()
1076                 .setSubscriptionIds(Set.of(TEST_SUBID1, TEST_SUBID2)).build();
1077         assertEquals(Set.of(TEST_SUBID1, TEST_SUBID2),
1078                 requestWithIds.networkCapabilities.getSubscriptionIds());
1079 
1080         assertFalse(requestWithIds.canBeSatisfiedBy(ncWithoutId));
1081         assertTrue(requestWithIds.canBeSatisfiedBy(ncWithOtherIds));
1082         assertFalse(requestWithIds.canBeSatisfiedBy(ncWithoutRequestedIds));
1083         assertTrue(requestWithIds.canBeSatisfiedBy(ncWithId));
1084         assertTrue(requestWithoutId.canBeSatisfiedBy(ncWithoutId));
1085         assertTrue(requestWithoutId.canBeSatisfiedBy(ncWithId));
1086     }
1087 
1088     @Test
testEqualsSubIds()1089     public void testEqualsSubIds() throws Exception {
1090         assertEquals(capsWithSubIds(), capsWithSubIds());
1091         assertNotEquals(capsWithSubIds(), capsWithSubIds(TEST_SUBID1));
1092         assertEquals(capsWithSubIds(TEST_SUBID1), capsWithSubIds(TEST_SUBID1));
1093         assertNotEquals(capsWithSubIds(TEST_SUBID1), capsWithSubIds(TEST_SUBID2));
1094         assertNotEquals(capsWithSubIds(TEST_SUBID1), capsWithSubIds(TEST_SUBID2, TEST_SUBID1));
1095         assertEquals(capsWithSubIds(TEST_SUBID1, TEST_SUBID2),
1096                 capsWithSubIds(TEST_SUBID2, TEST_SUBID1));
1097     }
1098 
1099     @Test
testLinkBandwidthKbps()1100     public void testLinkBandwidthKbps() {
1101         final NetworkCapabilities nc = new NetworkCapabilities();
1102         // The default value of LinkDown/UpstreamBandwidthKbps should be LINK_BANDWIDTH_UNSPECIFIED.
1103         assertEquals(LINK_BANDWIDTH_UNSPECIFIED, nc.getLinkDownstreamBandwidthKbps());
1104         assertEquals(LINK_BANDWIDTH_UNSPECIFIED, nc.getLinkUpstreamBandwidthKbps());
1105         nc.setLinkDownstreamBandwidthKbps(512);
1106         nc.setLinkUpstreamBandwidthKbps(128);
1107         assertEquals(512, nc.getLinkDownstreamBandwidthKbps());
1108         assertNotEquals(128, nc.getLinkDownstreamBandwidthKbps());
1109         assertEquals(128, nc.getLinkUpstreamBandwidthKbps());
1110         assertNotEquals(512, nc.getLinkUpstreamBandwidthKbps());
1111     }
1112 
getMaxTransport()1113     private int getMaxTransport() {
1114         if (!isAtLeastS() && MAX_TRANSPORT == TRANSPORT_USB) return MAX_TRANSPORT - 1;
1115         return MAX_TRANSPORT;
1116     }
1117 
1118     @Test
testSignalStrength()1119     public void testSignalStrength() {
1120         final NetworkCapabilities nc = new NetworkCapabilities();
1121         // The default value of signal strength should be SIGNAL_STRENGTH_UNSPECIFIED.
1122         assertEquals(SIGNAL_STRENGTH_UNSPECIFIED, nc.getSignalStrength());
1123         nc.setSignalStrength(-80);
1124         assertEquals(-80, nc.getSignalStrength());
1125         assertNotEquals(-50, nc.getSignalStrength());
1126     }
1127 
assertNoTransport(NetworkCapabilities nc)1128     private void assertNoTransport(NetworkCapabilities nc) {
1129         for (int i = MIN_TRANSPORT; i <= getMaxTransport(); i++) {
1130             assertFalse(nc.hasTransport(i));
1131         }
1132     }
1133 
1134     // Checks that all transport types from MIN_TRANSPORT to maxTransportType are set and all
1135     // transport types from maxTransportType + 1 to MAX_TRANSPORT are not set when positiveSequence
1136     // is true. If positiveSequence is false, then the check sequence is opposite.
checkCurrentTransportTypes(NetworkCapabilities nc, int maxTransportType, boolean positiveSequence)1137     private void checkCurrentTransportTypes(NetworkCapabilities nc, int maxTransportType,
1138             boolean positiveSequence) {
1139         for (int i = MIN_TRANSPORT; i <= maxTransportType; i++) {
1140             if (positiveSequence) {
1141                 assertTrue(nc.hasTransport(i));
1142             } else {
1143                 assertFalse(nc.hasTransport(i));
1144             }
1145         }
1146         for (int i = getMaxTransport(); i > maxTransportType; i--) {
1147             if (positiveSequence) {
1148                 assertFalse(nc.hasTransport(i));
1149             } else {
1150                 assertTrue(nc.hasTransport(i));
1151             }
1152         }
1153     }
1154 
1155     @Test
testMultipleTransportTypes()1156     public void testMultipleTransportTypes() {
1157         final NetworkCapabilities nc = new NetworkCapabilities();
1158         assertNoTransport(nc);
1159         // Test adding multiple transport types.
1160         for (int i = MIN_TRANSPORT; i <= getMaxTransport(); i++) {
1161             nc.addTransportType(i);
1162             checkCurrentTransportTypes(nc, i, true /* positiveSequence */);
1163         }
1164         // Test removing multiple transport types.
1165         for (int i = MIN_TRANSPORT; i <= getMaxTransport(); i++) {
1166             nc.removeTransportType(i);
1167             checkCurrentTransportTypes(nc, i, false /* positiveSequence */);
1168         }
1169         assertNoTransport(nc);
1170         nc.addTransportType(TRANSPORT_WIFI);
1171         assertTrue(nc.hasTransport(TRANSPORT_WIFI));
1172         assertFalse(nc.hasTransport(TRANSPORT_VPN));
1173         nc.addTransportType(TRANSPORT_VPN);
1174         assertTrue(nc.hasTransport(TRANSPORT_WIFI));
1175         assertTrue(nc.hasTransport(TRANSPORT_VPN));
1176         nc.removeTransportType(TRANSPORT_WIFI);
1177         assertFalse(nc.hasTransport(TRANSPORT_WIFI));
1178         assertTrue(nc.hasTransport(TRANSPORT_VPN));
1179         nc.removeTransportType(TRANSPORT_VPN);
1180         assertFalse(nc.hasTransport(TRANSPORT_WIFI));
1181         assertFalse(nc.hasTransport(TRANSPORT_VPN));
1182         assertNoTransport(nc);
1183     }
1184 
1185     @Test
testAddAndRemoveTransportType()1186     public void testAddAndRemoveTransportType() {
1187         final NetworkCapabilities nc = new NetworkCapabilities();
1188         try {
1189             nc.addTransportType(-1);
1190             fail("Should not set invalid transport type into addTransportType");
1191         } catch (IllegalArgumentException expected) { }
1192         try {
1193             nc.removeTransportType(-1);
1194             fail("Should not set invalid transport type into removeTransportType");
1195         } catch (IllegalArgumentException e) { }
1196     }
1197 
1198     /**
1199      * Test TransportInfo to verify redaction mechanism.
1200      */
1201     private static class TestTransportInfo implements TransportInfo {
1202         public final boolean locationRedacted;
1203         public final boolean localMacAddressRedacted;
1204         public final boolean settingsRedacted;
1205 
TestTransportInfo()1206         TestTransportInfo() {
1207             locationRedacted = false;
1208             localMacAddressRedacted = false;
1209             settingsRedacted = false;
1210         }
1211 
TestTransportInfo(boolean locationRedacted, boolean localMacAddressRedacted, boolean settingsRedacted)1212         TestTransportInfo(boolean locationRedacted,
1213                 boolean localMacAddressRedacted,
1214                 boolean settingsRedacted) {
1215             this.locationRedacted = locationRedacted;
1216             this.localMacAddressRedacted =
1217                     localMacAddressRedacted;
1218             this.settingsRedacted = settingsRedacted;
1219         }
1220 
1221         @Override
makeCopy(@etworkCapabilities.RedactionType long redactions)1222         public TransportInfo makeCopy(@NetworkCapabilities.RedactionType long redactions) {
1223             return new TestTransportInfo(
1224                     (redactions & NetworkCapabilities.REDACT_FOR_ACCESS_FINE_LOCATION) != 0,
1225                     (redactions & REDACT_FOR_LOCAL_MAC_ADDRESS) != 0,
1226                     (redactions & REDACT_FOR_NETWORK_SETTINGS) != 0
1227             );
1228         }
1229 
1230         @Override
getApplicableRedactions()1231         public @NetworkCapabilities.RedactionType long getApplicableRedactions() {
1232             return REDACT_FOR_ACCESS_FINE_LOCATION | REDACT_FOR_LOCAL_MAC_ADDRESS
1233                     | REDACT_FOR_NETWORK_SETTINGS;
1234         }
1235     }
1236 
1237     @Test
testBuilder()1238     public void testBuilder() {
1239         final int ownerUid = 1001;
1240         final int signalStrength = -80;
1241         final int requestUid = 10100;
1242         final int[] administratorUids = {ownerUid, 10001};
1243         final TelephonyNetworkSpecifier specifier = new TelephonyNetworkSpecifier(1);
1244         final TransportInfo transportInfo = new TransportInfo() {};
1245         final String ssid = "TEST_SSID";
1246         final String packageName = "com.google.test.networkcapabilities";
1247         final NetworkCapabilities.Builder capBuilder = new NetworkCapabilities.Builder()
1248                 .addTransportType(TRANSPORT_WIFI)
1249                 .addTransportType(TRANSPORT_CELLULAR)
1250                 .removeTransportType(TRANSPORT_CELLULAR)
1251                 .addCapability(NET_CAPABILITY_EIMS)
1252                 .addCapability(NET_CAPABILITY_CBS)
1253                 .removeCapability(NET_CAPABILITY_CBS)
1254                 .setAdministratorUids(administratorUids)
1255                 .setOwnerUid(ownerUid)
1256                 .setLinkDownstreamBandwidthKbps(512)
1257                 .setLinkUpstreamBandwidthKbps(128)
1258                 .setNetworkSpecifier(specifier)
1259                 .setTransportInfo(transportInfo)
1260                 .setSignalStrength(signalStrength)
1261                 .setSsid(ssid)
1262                 .setRequestorUid(requestUid)
1263                 .setRequestorPackageName(packageName);
1264         final Network network1 = new Network(100);
1265         final Network network2 = new Network(101);
1266         final List<Network> inputNetworks = List.of(network1, network2);
1267         if (isAtLeastT()) {
1268             capBuilder.setUnderlyingNetworks(inputNetworks);
1269         }
1270         final NetworkCapabilities nc = capBuilder.build();
1271         assertEquals(1, nc.getTransportTypes().length);
1272         assertEquals(TRANSPORT_WIFI, nc.getTransportTypes()[0]);
1273         assertTrue(nc.hasCapability(NET_CAPABILITY_EIMS));
1274         assertFalse(nc.hasCapability(NET_CAPABILITY_CBS));
1275         assertTrue(Arrays.equals(administratorUids, nc.getAdministratorUids()));
1276         assertEquals(ownerUid, nc.getOwnerUid());
1277         assertEquals(512, nc.getLinkDownstreamBandwidthKbps());
1278         assertNotEquals(128, nc.getLinkDownstreamBandwidthKbps());
1279         assertEquals(128, nc.getLinkUpstreamBandwidthKbps());
1280         assertNotEquals(512, nc.getLinkUpstreamBandwidthKbps());
1281         assertEquals(specifier, nc.getNetworkSpecifier());
1282         assertEquals(transportInfo, nc.getTransportInfo());
1283         assertEquals(signalStrength, nc.getSignalStrength());
1284         assertNotEquals(-50, nc.getSignalStrength());
1285         assertEquals(ssid, nc.getSsid());
1286         assertEquals(requestUid, nc.getRequestorUid());
1287         assertEquals(packageName, nc.getRequestorPackageName());
1288         if (isAtLeastT()) {
1289             final List<Network> outputNetworks = nc.getUnderlyingNetworks();
1290             assertEquals(network1, outputNetworks.get(0));
1291             assertEquals(network2, outputNetworks.get(1));
1292         }
1293         // Cannot assign null into NetworkCapabilities.Builder
1294         try {
1295             final NetworkCapabilities.Builder builder = new NetworkCapabilities.Builder(null);
1296             fail("Should not set null into NetworkCapabilities.Builder");
1297         } catch (NullPointerException expected) { }
1298         assertEquals(nc, new NetworkCapabilities.Builder(nc).build());
1299 
1300         if (isAtLeastS()) {
1301             final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
1302                     .setSubscriptionIds(Set.of(TEST_SUBID1)).build();
1303             assertEquals(Set.of(TEST_SUBID1), nc2.getSubscriptionIds());
1304         }
1305     }
1306 
1307     @Test
testBuilderWithoutDefaultCap()1308     public void testBuilderWithoutDefaultCap() {
1309         final NetworkCapabilities nc =
1310                 NetworkCapabilities.Builder.withoutDefaultCapabilities().build();
1311         assertFalse(nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED));
1312         assertFalse(nc.hasCapability(NET_CAPABILITY_TRUSTED));
1313         assertFalse(nc.hasCapability(NET_CAPABILITY_NOT_VPN));
1314         // Ensure test case fails if new net cap is added into default cap but no update here.
1315         assertEquals(0, nc.getCapabilities().length);
1316     }
1317 
1318     @Test
testRestrictCapabilitiesForTestNetworkByNotOwnerWithNonRestrictedNc()1319     public void testRestrictCapabilitiesForTestNetworkByNotOwnerWithNonRestrictedNc() {
1320         testRestrictCapabilitiesForTestNetworkWithNonRestrictedNc(false /* isOwner */);
1321     }
1322 
1323     @Test
testRestrictCapabilitiesForTestNetworkByOwnerWithNonRestrictedNc()1324     public void testRestrictCapabilitiesForTestNetworkByOwnerWithNonRestrictedNc() {
1325         testRestrictCapabilitiesForTestNetworkWithNonRestrictedNc(true /* isOwner */);
1326     }
1327 
testRestrictCapabilitiesForTestNetworkWithNonRestrictedNc(boolean isOwner)1328     private void testRestrictCapabilitiesForTestNetworkWithNonRestrictedNc(boolean isOwner) {
1329         final int ownerUid = 1234;
1330         final int signalStrength = -80;
1331         final int[] administratorUids = {1001, ownerUid};
1332         final TelephonyNetworkSpecifier specifier = new TelephonyNetworkSpecifier(TEST_SUBID1);
1333         final TransportInfo transportInfo = new TransportInfo() {};
1334         final NetworkCapabilities nonRestrictedNc = new NetworkCapabilities.Builder()
1335                 .addTransportType(TRANSPORT_CELLULAR)
1336                 .addCapability(NET_CAPABILITY_MMS)
1337                 .addCapability(NET_CAPABILITY_NOT_METERED)
1338                 .setAdministratorUids(administratorUids)
1339                 .setOwnerUid(ownerUid)
1340                 .setNetworkSpecifier(specifier)
1341                 .setSignalStrength(signalStrength)
1342                 .setTransportInfo(transportInfo)
1343                 .setSubscriptionIds(Set.of(TEST_SUBID1)).build();
1344         final int creatorUid = isOwner ? ownerUid : INVALID_UID;
1345         nonRestrictedNc.restrictCapabilitiesForTestNetwork(creatorUid);
1346 
1347         final NetworkCapabilities.Builder expectedNcBuilder = new NetworkCapabilities.Builder();
1348         // Non-UNRESTRICTED_TEST_NETWORKS_ALLOWED_TRANSPORTS will be removed and TRANSPORT_TEST will
1349         // be appended for non-restricted net cap.
1350         expectedNcBuilder.addTransportType(TRANSPORT_TEST);
1351         // Only TEST_NETWORKS_ALLOWED_CAPABILITIES will be kept. SubIds are only allowed for Test
1352         // Networks that only declare TRANSPORT_TEST.
1353         expectedNcBuilder.addCapability(NET_CAPABILITY_NOT_METERED)
1354                 .removeCapability(NET_CAPABILITY_TRUSTED)
1355                 .setSubscriptionIds(Set.of(TEST_SUBID1));
1356 
1357         expectedNcBuilder.setNetworkSpecifier(specifier)
1358                 .setSignalStrength(signalStrength).setTransportInfo(transportInfo);
1359         if (creatorUid == ownerUid) {
1360             // Only retain the owner and administrator UIDs if they match the app registering the
1361             // remote caller that registered the network.
1362             expectedNcBuilder.setAdministratorUids(new int[]{ownerUid}).setOwnerUid(ownerUid);
1363         }
1364 
1365         assertEquals(expectedNcBuilder.build(), nonRestrictedNc);
1366     }
1367 
1368     @Test
testRestrictCapabilitiesForTestNetworkRestrictedNc_NotOwner_NotCell()1369     public void testRestrictCapabilitiesForTestNetworkRestrictedNc_NotOwner_NotCell() {
1370         testRestrictCapabilitiesForTestNetworkWithRestrictedNc(
1371                 false /* isOwner */, false /* isCell */);
1372     }
1373 
1374     @Test
testRestrictCapabilitiesForTestNetworkRestrictedNc_Owner_NotCell()1375     public void testRestrictCapabilitiesForTestNetworkRestrictedNc_Owner_NotCell() {
1376         testRestrictCapabilitiesForTestNetworkWithRestrictedNc(
1377                 true /* isOwner */, false /* isCell */);
1378     }
1379 
1380     @Test
testRestrictCapabilitiesForTestNetworkRestrictedNc_NotOwner_Cell()1381     public void testRestrictCapabilitiesForTestNetworkRestrictedNc_NotOwner_Cell() {
1382         testRestrictCapabilitiesForTestNetworkWithRestrictedNc(
1383                 false /* isOwner */, true /* isCell */);
1384     }
1385 
1386     @Test
testRestrictCapabilitiesForTestNetworkRestrictedNc_Owner_Cell()1387     public void testRestrictCapabilitiesForTestNetworkRestrictedNc_Owner_Cell() {
1388         testRestrictCapabilitiesForTestNetworkWithRestrictedNc(
1389                 true /* isOwner */, false /* isCell */);
1390     }
1391 
testRestrictCapabilitiesForTestNetworkWithRestrictedNc( boolean isOwner, boolean isCell)1392     private void testRestrictCapabilitiesForTestNetworkWithRestrictedNc(
1393             boolean isOwner, boolean isCell) {
1394         final int ownerUid = 1234;
1395         final int signalStrength = -80;
1396         final int[] administratorUids = {1001, ownerUid};
1397         final TransportInfo transportInfo = new TransportInfo() {};
1398         // No NetworkSpecifier is set because after performing restrictCapabilitiesForTestNetwork
1399         // the networkCapabilities will contain more than one transport type. However,
1400         // networkCapabilities must have a single transport specified to use NetworkSpecifier. Thus,
1401         // do not verify this part since it's verified in other tests.
1402         final NetworkCapabilities.Builder restrictedNcBuilder = new NetworkCapabilities.Builder()
1403                 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED)
1404                 .addCapability(NET_CAPABILITY_MMS)
1405                 .addCapability(NET_CAPABILITY_NOT_METERED)
1406                 .setAdministratorUids(administratorUids)
1407                 .setOwnerUid(ownerUid)
1408                 .setSignalStrength(signalStrength)
1409                 .setTransportInfo(transportInfo)
1410                 .setSubscriptionIds(Set.of(TEST_SUBID1));
1411         for (int cap : TEST_NETWORKS_EXTRA_ALLOWED_CAPS_ON_NON_CELL) {
1412             restrictedNcBuilder.addCapability(cap);
1413         }
1414 
1415         if (isCell) {
1416             restrictedNcBuilder.addTransportType(TRANSPORT_CELLULAR);
1417         }
1418         final NetworkCapabilities restrictedNc = restrictedNcBuilder.build();
1419 
1420         final int creatorUid = isOwner ? ownerUid : INVALID_UID;
1421         restrictedNc.restrictCapabilitiesForTestNetwork(creatorUid);
1422 
1423         final NetworkCapabilities.Builder expectedNcBuilder = new NetworkCapabilities.Builder()
1424                 .removeCapability(NET_CAPABILITY_NOT_RESTRICTED);
1425 
1426         if (isCell) {
1427             // If the test network is restricted, then the network may declare any transport, and
1428             // appended with TRANSPORT_TEST.
1429             expectedNcBuilder.addTransportType(TRANSPORT_CELLULAR);
1430         } else {
1431             // If the test network only has TRANSPORT_TEST, then it can keep the subscription IDs.
1432             expectedNcBuilder.setSubscriptionIds(Set.of(TEST_SUBID1));
1433         }
1434         expectedNcBuilder.addTransportType(TRANSPORT_TEST);
1435 
1436         // Only TEST_NETWORKS_ALLOWED_CAPABILITIES will be kept.
1437         expectedNcBuilder.addCapability(NET_CAPABILITY_NOT_METERED);
1438         expectedNcBuilder.removeCapability(NET_CAPABILITY_TRUSTED);
1439 
1440         if (!isCell) {
1441             for (int cap : TEST_NETWORKS_EXTRA_ALLOWED_CAPS_ON_NON_CELL) {
1442                 expectedNcBuilder.addCapability(cap);
1443             }
1444         }
1445 
1446         expectedNcBuilder.setSignalStrength(signalStrength).setTransportInfo(transportInfo);
1447         if (creatorUid == ownerUid) {
1448             // Only retain the owner and administrator UIDs if they match the app registering the
1449             // remote caller that registered the network.
1450             expectedNcBuilder.setAdministratorUids(new int[]{ownerUid}).setOwnerUid(ownerUid);
1451         }
1452 
1453         assertEquals(expectedNcBuilder.build(), restrictedNc);
1454     }
1455 
1456     @Test
testDescribeCapsDifferences()1457     public void testDescribeCapsDifferences() throws Exception {
1458         final NetworkCapabilities nc1 = new NetworkCapabilities.Builder()
1459                 .addCapability(NET_CAPABILITY_MMS)
1460                 .addCapability(NET_CAPABILITY_OEM_PAID)
1461                 .addCapability(NET_CAPABILITY_INTERNET)
1462                 .build();
1463         final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
1464                 .addCapability(NET_CAPABILITY_CAPTIVE_PORTAL)
1465                 .addCapability(NET_CAPABILITY_SUPL)
1466                 .addCapability(NET_CAPABILITY_VALIDATED)
1467                 .addCapability(NET_CAPABILITY_INTERNET)
1468                 .build();
1469         assertEquals("-MMS-OEM_PAID+SUPL+VALIDATED+CAPTIVE_PORTAL",
1470                 nc2.describeCapsDifferencesFrom(nc1));
1471         assertEquals("-SUPL-VALIDATED-CAPTIVE_PORTAL+MMS+OEM_PAID",
1472                 nc1.describeCapsDifferencesFrom(nc2));
1473     }
1474 
1475     @Test
testInvalidCapability()1476     public void testInvalidCapability() {
1477         final int invalidCapability = Integer.MAX_VALUE;
1478         // Passing invalid capability does not throw
1479         final NetworkCapabilities nc1 = new NetworkCapabilities.Builder()
1480                 .addCapability(NET_CAPABILITY_INTERNET)
1481                 .addForbiddenCapability(NET_CAPABILITY_NOT_ROAMING)
1482                 .removeCapability(invalidCapability)
1483                 .removeForbiddenCapability(invalidCapability)
1484                 .addCapability(invalidCapability)
1485                 .addForbiddenCapability(invalidCapability)
1486                 .build();
1487 
1488         final NetworkCapabilities nc2 = new NetworkCapabilities.Builder()
1489                 .addCapability(NET_CAPABILITY_INTERNET)
1490                 .addForbiddenCapability(NET_CAPABILITY_NOT_ROAMING)
1491                 .build();
1492 
1493         // nc1 and nc2 are the same since invalid capability is ignored
1494         assertEquals(nc1, nc2);
1495     }
1496 }
1497