• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2019 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.backup;
18 
19 import static android.Manifest.permission.BACKUP;
20 import static android.Manifest.permission.DUMP;
21 import static android.Manifest.permission.INTERACT_ACROSS_USERS_FULL;
22 import static android.Manifest.permission.PACKAGE_USAGE_STATS;
23 
24 import static com.android.server.backup.testing.TransportData.backupTransport;
25 
26 import static com.google.common.truth.Truth.assertThat;
27 
28 import static org.junit.Assert.assertEquals;
29 import static org.mockito.ArgumentMatchers.any;
30 import static org.mockito.ArgumentMatchers.anyString;
31 import static org.mockito.Mockito.doNothing;
32 import static org.mockito.Mockito.mock;
33 import static org.mockito.Mockito.never;
34 import static org.mockito.Mockito.spy;
35 import static org.mockito.Mockito.verify;
36 import static org.robolectric.Shadows.shadowOf;
37 import static org.testng.Assert.expectThrows;
38 
39 import android.annotation.UserIdInt;
40 import android.app.Application;
41 import android.app.backup.IBackupManagerMonitor;
42 import android.app.backup.IBackupObserver;
43 import android.app.backup.IFullBackupRestoreObserver;
44 import android.app.backup.ISelectBackupTransportCallback;
45 import android.content.Context;
46 import android.content.Intent;
47 import android.content.pm.UserInfo;
48 import android.os.IBinder;
49 import android.os.ParcelFileDescriptor;
50 import android.os.Process;
51 import android.os.UserHandle;
52 import android.os.UserManager;
53 import android.platform.test.annotations.Presubmit;
54 import android.util.SparseArray;
55 
56 import com.android.server.SystemService.TargetUser;
57 import com.android.server.backup.testing.TransportData;
58 import com.android.server.testing.shadows.ShadowApplicationPackageManager;
59 import com.android.server.testing.shadows.ShadowBinder;
60 import com.android.server.testing.shadows.ShadowEnvironment;
61 import com.android.server.testing.shadows.ShadowSystemServiceRegistry;
62 import com.android.server.testing.shadows.ShadowUserManager;
63 
64 import org.junit.Before;
65 import org.junit.Test;
66 import org.junit.runner.RunWith;
67 import org.mockito.Mock;
68 import org.mockito.MockitoAnnotations;
69 import org.robolectric.RobolectricTestRunner;
70 import org.robolectric.RuntimeEnvironment;
71 import org.robolectric.annotation.Config;
72 import org.robolectric.shadow.api.Shadow;
73 import org.robolectric.shadows.ShadowContextWrapper;
74 
75 import java.io.File;
76 import java.io.FileDescriptor;
77 import java.io.IOException;
78 import java.io.PrintWriter;
79 import java.io.StringWriter;
80 
81 /** Tests for {@link BackupManagerService}. */
82 @RunWith(RobolectricTestRunner.class)
83 @Config(
84         shadows = {
85                 ShadowApplicationPackageManager.class,
86                 ShadowBinder.class,
87                 ShadowUserManager.class,
88                 ShadowEnvironment.class,
89                 ShadowSystemServiceRegistry.class
90         })
91 @Presubmit
92 public class BackupManagerServiceRoboTest {
93     private static final String TEST_PACKAGE = "package";
94     private static final String TEST_TRANSPORT = "transport";
95     private static final String[] ADB_TEST_PACKAGES = {TEST_PACKAGE};
96 
97     private Context mContext;
98     private ShadowContextWrapper mShadowContext;
99     private ShadowUserManager mShadowUserManager;
100     @UserIdInt private int mUserOneId;
101     @UserIdInt private int mUserTwoId;
102     @Mock private UserBackupManagerService mUserSystemService;
103     @Mock private UserBackupManagerService mUserOneService;
104     @Mock private UserBackupManagerService mUserTwoService;
105 
106     /** Setup */
107     @Before
setUp()108     public void setUp() throws Exception {
109         MockitoAnnotations.initMocks(this);
110 
111         Application application = RuntimeEnvironment.application;
112         mContext = application;
113         mShadowContext = shadowOf(application);
114         mShadowUserManager = Shadow.extract(UserManager.get(application));
115 
116         mUserOneId = UserHandle.USER_SYSTEM + 1;
117         mUserTwoId = mUserOneId + 1;
118         mShadowUserManager.addUser(mUserOneId, "mUserOneId", 0);
119         mShadowUserManager.addUser(mUserTwoId, "mUserTwoId", 0);
120 
121         mShadowContext.grantPermissions(BACKUP);
122         mShadowContext.grantPermissions(INTERACT_ACROSS_USERS_FULL);
123 
124         ShadowBinder.setCallingUid(Process.SYSTEM_UID);
125     }
126 
127     /** Test that the service registers users. */
128     @Test
testStartServiceForUser_registersUser()129     public void testStartServiceForUser_registersUser() throws Exception {
130         BackupManagerService backupManagerService = createService();
131         backupManagerService.setBackupServiceActive(mUserOneId, true);
132 
133         backupManagerService.startServiceForUser(mUserOneId);
134 
135         SparseArray<UserBackupManagerService> serviceUsers = backupManagerService.getUserServices();
136         assertThat(serviceUsers.size()).isEqualTo(1);
137         assertThat(serviceUsers.get(mUserOneId)).isNotNull();
138     }
139 
140     /** Test that the service registers users. */
141     @Test
testStartServiceForUser_withServiceInstance_registersUser()142     public void testStartServiceForUser_withServiceInstance_registersUser() throws Exception {
143         BackupManagerService backupManagerService = createService();
144         backupManagerService.setBackupServiceActive(mUserOneId, true);
145 
146         backupManagerService.startServiceForUser(mUserOneId, mUserOneService);
147 
148         SparseArray<UserBackupManagerService> serviceUsers = backupManagerService.getUserServices();
149         assertThat(serviceUsers.size()).isEqualTo(1);
150         assertThat(serviceUsers.get(mUserOneId)).isEqualTo(mUserOneService);
151     }
152 
153     /** Test that the service unregisters users when stopped. */
154     @Test
testStopServiceForUser_forRegisteredUser_unregistersCorrectUser()155     public void testStopServiceForUser_forRegisteredUser_unregistersCorrectUser() throws Exception {
156         BackupManagerService backupManagerService =
157                 createServiceAndRegisterUser(mUserOneId, mUserOneService);
158         backupManagerService.startServiceForUser(mUserTwoId, mUserTwoService);
159         ShadowBinder.setCallingUid(Process.SYSTEM_UID);
160 
161         backupManagerService.stopServiceForUser(mUserOneId);
162 
163         SparseArray<UserBackupManagerService> serviceUsers = backupManagerService.getUserServices();
164         assertThat(serviceUsers.size()).isEqualTo(1);
165         assertThat(serviceUsers.get(mUserOneId)).isNull();
166         assertThat(serviceUsers.get(mUserTwoId)).isEqualTo(mUserTwoService);
167     }
168 
169     /** Test that the service unregisters users when stopped. */
170     @Test
testStopServiceForUser_forRegisteredUser_tearsDownCorrectUser()171     public void testStopServiceForUser_forRegisteredUser_tearsDownCorrectUser() throws Exception {
172         BackupManagerService backupManagerService =
173                 createServiceAndRegisterUser(mUserOneId, mUserOneService);
174         backupManagerService.setBackupServiceActive(mUserTwoId, true);
175         backupManagerService.startServiceForUser(mUserTwoId, mUserTwoService);
176 
177         backupManagerService.stopServiceForUser(mUserOneId);
178 
179         verify(mUserOneService).tearDownService();
180         verify(mUserTwoService, never()).tearDownService();
181     }
182 
183     /** Test that the service unregisters users when stopped. */
184     @Test
testStopServiceForUser_forUnknownUser_doesNothing()185     public void testStopServiceForUser_forUnknownUser_doesNothing() throws Exception {
186         BackupManagerService backupManagerService = createService();
187         backupManagerService.setBackupServiceActive(mUserOneId, true);
188         ShadowBinder.setCallingUid(Process.SYSTEM_UID);
189 
190         backupManagerService.stopServiceForUser(mUserOneId);
191 
192         SparseArray<UserBackupManagerService> serviceUsers = backupManagerService.getUserServices();
193         assertThat(serviceUsers.size()).isEqualTo(0);
194     }
195 
196     // ---------------------------------------------
197     // Backup agent tests
198     // ---------------------------------------------
199 
200     /** Test that the backup service routes methods correctly to the user that requests it. */
201     @Test
testDataChanged_onRegisteredUser_callsMethodForUser()202     public void testDataChanged_onRegisteredUser_callsMethodForUser() throws Exception {
203         BackupManagerService backupManagerService = createService();
204         registerUser(backupManagerService, mUserOneId, mUserOneService);
205         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
206 
207         backupManagerService.dataChanged(mUserOneId, TEST_PACKAGE);
208 
209         verify(mUserOneService).dataChanged(TEST_PACKAGE);
210     }
211 
212     /** Test that the backup service does not route methods for non-registered users. */
213     @Test
testDataChanged_onUnknownUser_doesNotPropagateCall()214     public void testDataChanged_onUnknownUser_doesNotPropagateCall() throws Exception {
215         BackupManagerService backupManagerService = createService();
216         registerUser(backupManagerService, mUserOneId, mUserOneService);
217         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
218 
219         backupManagerService.dataChanged(mUserTwoId, TEST_PACKAGE);
220 
221         verify(mUserOneService, never()).dataChanged(TEST_PACKAGE);
222     }
223 
224     /** Test that the backup service routes methods correctly to the user that requests it. */
225     @Test
testAgentConnected_onRegisteredUser_callsMethodForUser()226     public void testAgentConnected_onRegisteredUser_callsMethodForUser() throws Exception {
227         BackupManagerService backupManagerService = createService();
228         registerUser(backupManagerService, mUserOneId, mUserOneService);
229         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
230         IBinder agentBinder = mock(IBinder.class);
231 
232         backupManagerService.agentConnected(mUserOneId, TEST_PACKAGE, agentBinder);
233 
234         verify(mUserOneService).agentConnected(TEST_PACKAGE, agentBinder);
235     }
236 
237     /** Test that the backup service does not route methods for non-registered users. */
238     @Test
testAgentConnected_onUnknownUser_doesNotPropagateCall()239     public void testAgentConnected_onUnknownUser_doesNotPropagateCall() throws Exception {
240         BackupManagerService backupManagerService = createService();
241         registerUser(backupManagerService, mUserOneId, mUserOneService);
242         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
243         IBinder agentBinder = mock(IBinder.class);
244 
245         backupManagerService.agentConnected(mUserTwoId, TEST_PACKAGE, agentBinder);
246 
247         verify(mUserOneService, never()).agentConnected(TEST_PACKAGE, agentBinder);
248     }
249 
250     /** Test that the backup service routes methods correctly to the user that requests it. */
251     @Test
testOpComplete_onRegisteredUser_callsMethodForUser()252     public void testOpComplete_onRegisteredUser_callsMethodForUser() throws Exception {
253         BackupManagerService backupManagerService = createService();
254         registerUser(backupManagerService, mUserOneId, mUserOneService);
255         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
256 
257         backupManagerService.opComplete(mUserOneId, /* token */ 0, /* result */ 0L);
258 
259         verify(mUserOneService).opComplete(/* token */ 0, /* result */ 0L);
260     }
261 
262     /** Test that the backup service does not route methods for non-registered users. */
263     @Test
testOpComplete_onUnknownUser_doesNotPropagateCall()264     public void testOpComplete_onUnknownUser_doesNotPropagateCall() throws Exception {
265         BackupManagerService backupManagerService = createService();
266         registerUser(backupManagerService, mUserOneId, mUserOneService);
267         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
268 
269         backupManagerService.opComplete(mUserTwoId, /* token */ 0, /* result */ 0L);
270 
271         verify(mUserOneService, never()).opComplete(/* token */ 0, /* result */ 0L);
272     }
273 
274     // ---------------------------------------------
275     // Transport tests
276     // ---------------------------------------------
277 
278     /** Test that the backup service routes methods correctly to the user that requests it. */
279     @Test
testInitializeTransports_onRegisteredUser_callsMethodForUser()280     public void testInitializeTransports_onRegisteredUser_callsMethodForUser() throws Exception {
281         BackupManagerService backupManagerService = createService();
282         registerUser(backupManagerService, mUserOneId, mUserOneService);
283         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
284         String[] transports = {TEST_TRANSPORT};
285 
286         backupManagerService.initializeTransports(mUserOneId, transports, /* observer */ null);
287 
288         verify(mUserOneService).initializeTransports(transports, /* observer */ null);
289     }
290 
291     /** Test that the backup service does not route methods for non-registered users. */
292     @Test
testInitializeTransports_onUnknownUser_doesNotPropagateCall()293     public void testInitializeTransports_onUnknownUser_doesNotPropagateCall() throws Exception {
294         BackupManagerService backupManagerService = createService();
295         registerUser(backupManagerService, mUserOneId, mUserOneService);
296         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
297         String[] transports = {TEST_TRANSPORT};
298 
299         backupManagerService.initializeTransports(mUserTwoId, transports, /* observer */ null);
300 
301         verify(mUserOneService, never()).initializeTransports(transports, /* observer */ null);
302     }
303 
304     /** Test that the backup service routes methods correctly to the user that requests it. */
305     @Test
testClearBackupData_onRegisteredUser_callsMethodForUser()306     public void testClearBackupData_onRegisteredUser_callsMethodForUser() throws Exception {
307         BackupManagerService backupManagerService = createService();
308         registerUser(backupManagerService, mUserOneId, mUserOneService);
309         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
310 
311         backupManagerService.clearBackupData(mUserOneId, TEST_TRANSPORT, TEST_PACKAGE);
312 
313         verify(mUserOneService).clearBackupData(TEST_TRANSPORT, TEST_PACKAGE);
314     }
315 
316     /** Test that the backup service does not route methods for non-registered users. */
317     @Test
testClearBackupData_onUnknownUser_doesNotPropagateCall()318     public void testClearBackupData_onUnknownUser_doesNotPropagateCall() throws Exception {
319         BackupManagerService backupManagerService = createService();
320         registerUser(backupManagerService, mUserOneId, mUserOneService);
321         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
322 
323         backupManagerService.clearBackupData(mUserTwoId, TEST_TRANSPORT, TEST_PACKAGE);
324 
325         verify(mUserOneService, never()).clearBackupData(TEST_TRANSPORT, TEST_PACKAGE);
326     }
327 
328     /** Test that the backup service routes methods correctly to the user that requests it. */
329     @Test
testGetCurrentTransport_onRegisteredUser_callsMethodForUser()330     public void testGetCurrentTransport_onRegisteredUser_callsMethodForUser() throws Exception {
331         BackupManagerService backupManagerService = createService();
332         registerUser(backupManagerService, mUserOneId, mUserOneService);
333         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
334 
335         backupManagerService.getCurrentTransport(mUserOneId);
336 
337         verify(mUserOneService).getCurrentTransport();
338     }
339 
340     /** Test that the backup service does not route methods for non-registered users. */
341     @Test
testGetCurrentTransport_onUnknownUser_doesNotPropagateCall()342     public void testGetCurrentTransport_onUnknownUser_doesNotPropagateCall() throws Exception {
343         BackupManagerService backupManagerService = createService();
344         registerUser(backupManagerService, mUserOneId, mUserOneService);
345         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
346 
347         backupManagerService.getCurrentTransport(mUserTwoId);
348 
349         verify(mUserOneService, never()).getCurrentTransport();
350     }
351 
352     /** Test that the backup service routes methods correctly to the user that requests it. */
353     @Test
testGetCurrentTransportComponent_onRegisteredUser_callsMethodForUser()354     public void testGetCurrentTransportComponent_onRegisteredUser_callsMethodForUser()
355             throws Exception {
356         BackupManagerService backupManagerService = createService();
357         registerUser(backupManagerService, mUserOneId, mUserOneService);
358         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
359 
360         backupManagerService.getCurrentTransportComponent(mUserOneId);
361 
362         verify(mUserOneService).getCurrentTransportComponent();
363     }
364 
365     /** Test that the backup service does not route methods for non-registered users. */
366     @Test
testGetCurrentTransportComponent_onUnknownUser_doesNotPropagateCall()367     public void testGetCurrentTransportComponent_onUnknownUser_doesNotPropagateCall()
368             throws Exception {
369         BackupManagerService backupManagerService = createService();
370         registerUser(backupManagerService, mUserOneId, mUserOneService);
371         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
372 
373         backupManagerService.getCurrentTransportComponent(mUserTwoId);
374 
375         verify(mUserOneService, never()).getCurrentTransportComponent();
376     }
377 
378     /** Test that the backup service routes methods correctly to the user that requests it. */
379     @Test
testListAllTransports_onRegisteredUser_callsMethodForUser()380     public void testListAllTransports_onRegisteredUser_callsMethodForUser() throws Exception {
381         BackupManagerService backupManagerService = createService();
382         registerUser(backupManagerService, mUserOneId, mUserOneService);
383         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
384 
385         backupManagerService.listAllTransports(mUserOneId);
386 
387         verify(mUserOneService).listAllTransports();
388     }
389 
390     /** Test that the backup service does not route methods for non-registered users. */
391     @Test
testListAllTransports_onUnknownUser_doesNotPropagateCall()392     public void testListAllTransports_onUnknownUser_doesNotPropagateCall() throws Exception {
393         BackupManagerService backupManagerService = createService();
394         registerUser(backupManagerService, mUserOneId, mUserOneService);
395         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
396 
397         backupManagerService.listAllTransports(mUserTwoId);
398 
399         verify(mUserOneService, never()).listAllTransports();
400     }
401 
402     /** Test that the backup service routes methods correctly to the user that requests it. */
403     @Test
testListAllTransportComponents_onRegisteredUser_callsMethodForUser()404     public void testListAllTransportComponents_onRegisteredUser_callsMethodForUser()
405             throws Exception {
406         BackupManagerService backupManagerService = createService();
407         registerUser(backupManagerService, mUserOneId, mUserOneService);
408         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
409 
410         backupManagerService.listAllTransportComponents(mUserOneId);
411 
412         verify(mUserOneService).listAllTransportComponents();
413     }
414 
415     /** Test that the backup service does not route methods for non-registered users. */
416     @Test
testListAllTransportComponents_onUnknownUser_doesNotPropagateCall()417     public void testListAllTransportComponents_onUnknownUser_doesNotPropagateCall()
418             throws Exception {
419         BackupManagerService backupManagerService = createService();
420         registerUser(backupManagerService, mUserOneId, mUserOneService);
421         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
422 
423         backupManagerService.listAllTransportComponents(mUserTwoId);
424 
425         verify(mUserOneService, never()).listAllTransportComponents();
426     }
427 
428     /** Test that the backup service routes methods correctly to the user that requests it. */
429     @Test
testSelectBackupTransport_onRegisteredUser_callsMethodForUser()430     public void testSelectBackupTransport_onRegisteredUser_callsMethodForUser() throws Exception {
431         BackupManagerService backupManagerService = createService();
432         registerUser(backupManagerService, mUserOneId, mUserOneService);
433         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
434 
435         backupManagerService.selectBackupTransport(mUserOneId, TEST_TRANSPORT);
436 
437         verify(mUserOneService).selectBackupTransport(TEST_TRANSPORT);
438     }
439 
440     /** Test that the backup service does not route methods for non-registered users. */
441     @Test
testSelectBackupTransport_onUnknownUser_doesNotPropagateCall()442     public void testSelectBackupTransport_onUnknownUser_doesNotPropagateCall() throws Exception {
443         BackupManagerService backupManagerService = createService();
444         registerUser(backupManagerService, mUserOneId, mUserOneService);
445         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
446 
447         backupManagerService.selectBackupTransport(mUserTwoId, TEST_TRANSPORT);
448 
449         verify(mUserOneService, never()).selectBackupTransport(TEST_TRANSPORT);
450     }
451 
452     /** Test that the backup service routes methods correctly to the user that requests it. */
453     @Test
testSelectTransportAsync_onRegisteredUser_callsMethodForUser()454     public void testSelectTransportAsync_onRegisteredUser_callsMethodForUser() throws Exception {
455         BackupManagerService backupManagerService = createService();
456         registerUser(backupManagerService, mUserOneId, mUserOneService);
457         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
458         TransportData transport = backupTransport();
459         ISelectBackupTransportCallback callback = mock(ISelectBackupTransportCallback.class);
460 
461         backupManagerService.selectBackupTransportAsync(
462                 mUserOneId, transport.getTransportComponent(), callback);
463 
464         verify(mUserOneService)
465                 .selectBackupTransportAsync(transport.getTransportComponent(), callback);
466     }
467 
468     /** Test that the backup service does not route methods for non-registered users. */
469     @Test
testSelectBackupTransportAsync_onUnknownUser_doesNotPropagateCall()470     public void testSelectBackupTransportAsync_onUnknownUser_doesNotPropagateCall()
471             throws Exception {
472         BackupManagerService backupManagerService = createService();
473         registerUser(backupManagerService, mUserOneId, mUserOneService);
474         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
475         TransportData transport = backupTransport();
476         ISelectBackupTransportCallback callback = mock(ISelectBackupTransportCallback.class);
477 
478         backupManagerService.selectBackupTransportAsync(
479                 mUserTwoId, transport.getTransportComponent(), callback);
480 
481         verify(mUserOneService, never())
482                 .selectBackupTransportAsync(transport.getTransportComponent(), callback);
483     }
484 
485     /** Test that the backup service routes methods correctly to the user that requests it. */
486     @Test
testGetConfigurationIntent_onRegisteredUser_callsMethodForUser()487     public void testGetConfigurationIntent_onRegisteredUser_callsMethodForUser() throws Exception {
488         BackupManagerService backupManagerService = createService();
489         registerUser(backupManagerService, mUserOneId, mUserOneService);
490         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
491 
492         backupManagerService.getConfigurationIntent(mUserOneId, TEST_TRANSPORT);
493 
494         verify(mUserOneService).getConfigurationIntent(TEST_TRANSPORT);
495     }
496 
497     /** Test that the backup service does not route methods for non-registered users. */
498     @Test
testGetConfigurationIntent_onUnknownUser_doesNotPropagateCall()499     public void testGetConfigurationIntent_onUnknownUser_doesNotPropagateCall() throws Exception {
500         BackupManagerService backupManagerService = createService();
501         registerUser(backupManagerService, mUserOneId, mUserOneService);
502         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
503 
504         backupManagerService.getConfigurationIntent(mUserTwoId, TEST_TRANSPORT);
505 
506         verify(mUserOneService, never()).getConfigurationIntent(TEST_TRANSPORT);
507     }
508 
509     /** Test that the backup service routes methods correctly to the user that requests it. */
510     @Test
testGetDestinationString_onRegisteredUser_callsMethodForUser()511     public void testGetDestinationString_onRegisteredUser_callsMethodForUser() throws Exception {
512         BackupManagerService backupManagerService = createService();
513         registerUser(backupManagerService, mUserOneId, mUserOneService);
514         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
515 
516         backupManagerService.getDestinationString(mUserOneId, TEST_TRANSPORT);
517 
518         verify(mUserOneService).getDestinationString(TEST_TRANSPORT);
519     }
520 
521     /** Test that the backup service does not route methods for non-registered users. */
522     @Test
testGetDestinationString_onUnknownUser_doesNotPropagateCall()523     public void testGetDestinationString_onUnknownUser_doesNotPropagateCall() throws Exception {
524         BackupManagerService backupManagerService = createService();
525         registerUser(backupManagerService, mUserOneId, mUserOneService);
526         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
527 
528         backupManagerService.getDestinationString(mUserTwoId, TEST_TRANSPORT);
529 
530         verify(mUserOneService, never()).getDestinationString(TEST_TRANSPORT);
531     }
532 
533     /** Test that the backup service routes methods correctly to the user that requests it. */
534     @Test
testGetDataManagementIntent_onRegisteredUser_callsMethodForUser()535     public void testGetDataManagementIntent_onRegisteredUser_callsMethodForUser() throws Exception {
536         BackupManagerService backupManagerService = createService();
537         registerUser(backupManagerService, mUserOneId, mUserOneService);
538         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
539 
540         backupManagerService.getDataManagementIntent(mUserOneId, TEST_TRANSPORT);
541 
542         verify(mUserOneService).getDataManagementIntent(TEST_TRANSPORT);
543     }
544 
545     /** Test that the backup service does not route methods for non-registered users. */
546     @Test
testGetDataManagementIntent_onUnknownUser_doesNotPropagateCall()547     public void testGetDataManagementIntent_onUnknownUser_doesNotPropagateCall() throws Exception {
548         BackupManagerService backupManagerService = createService();
549         registerUser(backupManagerService, mUserOneId, mUserOneService);
550         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
551 
552         backupManagerService.getDataManagementIntent(mUserTwoId, TEST_TRANSPORT);
553 
554         verify(mUserOneService, never()).getDataManagementIntent(TEST_TRANSPORT);
555     }
556 
557     /** Test that the backup service routes methods correctly to the user that requests it. */
558     @Test
testGetDataManagementLabel_onRegisteredUser_callsMethodForUser()559     public void testGetDataManagementLabel_onRegisteredUser_callsMethodForUser() throws Exception {
560         BackupManagerService backupManagerService = createService();
561         registerUser(backupManagerService, mUserOneId, mUserOneService);
562         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
563 
564         backupManagerService.getDataManagementLabel(mUserOneId, TEST_TRANSPORT);
565 
566         verify(mUserOneService).getDataManagementLabel(TEST_TRANSPORT);
567     }
568 
569     /** Test that the backup service does not route methods for non-registered users. */
570     @Test
testGetDataManagementLabel_onUnknownUser_doesNotPropagateCall()571     public void testGetDataManagementLabel_onUnknownUser_doesNotPropagateCall() throws Exception {
572         BackupManagerService backupManagerService = createService();
573         registerUser(backupManagerService, mUserOneId, mUserOneService);
574         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
575 
576         backupManagerService.getDataManagementLabel(mUserTwoId, TEST_TRANSPORT);
577 
578         verify(mUserOneService, never()).getDataManagementLabel(TEST_TRANSPORT);
579     }
580 
581     /** Test that the backup service routes methods correctly to the user that requests it. */
582     @Test
testUpdateTransportAttributes_onRegisteredUser_callsMethodForUser()583     public void testUpdateTransportAttributes_onRegisteredUser_callsMethodForUser()
584             throws Exception {
585         BackupManagerService backupManagerService = createService();
586         registerUser(backupManagerService, mUserOneId, mUserOneService);
587         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
588         TransportData transport = backupTransport();
589         Intent configurationIntent = new Intent();
590         Intent dataManagementIntent = new Intent();
591 
592         backupManagerService.updateTransportAttributes(
593                 mUserOneId,
594                 transport.getTransportComponent(),
595                 transport.transportName,
596                 configurationIntent,
597                 "currentDestinationString",
598                 dataManagementIntent,
599                 "dataManagementLabel");
600 
601         verify(mUserOneService)
602                 .updateTransportAttributes(
603                         transport.getTransportComponent(),
604                         transport.transportName,
605                         configurationIntent,
606                         "currentDestinationString",
607                         dataManagementIntent,
608                         "dataManagementLabel");
609     }
610 
611     /** Test that the backup service does not route methods for non-registered users. */
612     @Test
testUpdateTransportAttributes_onUnknownUser_doesNotPropagateCall()613     public void testUpdateTransportAttributes_onUnknownUser_doesNotPropagateCall()
614             throws Exception {
615         BackupManagerService backupManagerService = createService();
616         registerUser(backupManagerService, mUserOneId, mUserOneService);
617         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
618         TransportData transport = backupTransport();
619         Intent configurationIntent = new Intent();
620         Intent dataManagementIntent = new Intent();
621 
622         backupManagerService.updateTransportAttributes(
623                 mUserTwoId,
624                 transport.getTransportComponent(),
625                 transport.transportName,
626                 configurationIntent,
627                 "currentDestinationString",
628                 dataManagementIntent,
629                 "dataManagementLabel");
630 
631         verify(mUserOneService, never())
632                 .updateTransportAttributes(
633                         transport.getTransportComponent(),
634                         transport.transportName,
635                         configurationIntent,
636                         "currentDestinationString",
637                         dataManagementIntent,
638                         "dataManagementLabel");
639     }
640 
641     // ---------------------------------------------
642     // Settings tests
643     // ---------------------------------------------
644 
645     /**
646      * Test that the backup services throws a {@link SecurityException} if the caller does not have
647      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
648      */
649     @Test
testSetBackupEnabled_withoutPermission_throwsSecurityExceptionForNonCallingUser()650     public void testSetBackupEnabled_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
651         BackupManagerService backupManagerService = createService();
652         registerUser(backupManagerService, mUserOneId, mUserOneService);
653         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
654 
655         expectThrows(
656                 SecurityException.class,
657                 () -> backupManagerService.setBackupEnabled(mUserTwoId, true));
658     }
659 
660     /**
661      * Test that the backup service does not throw a {@link SecurityException} if the caller has
662      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
663      */
664     @Test
testSetBackupEnabled_withPermission_propagatesForNonCallingUser()665     public void testSetBackupEnabled_withPermission_propagatesForNonCallingUser() {
666         BackupManagerService backupManagerService = createService();
667         registerUser(backupManagerService, mUserOneId, mUserOneService);
668         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
669 
670         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ true);
671 
672         backupManagerService.setBackupEnabled(mUserTwoId, true);
673 
674         verify(mUserTwoService).setBackupEnabled(true);
675     }
676 
677     /** Test that the backup service routes methods correctly to the user that requests it. */
678     @Test
testSetBackupEnabled_onRegisteredUser_callsMethodForUser()679     public void testSetBackupEnabled_onRegisteredUser_callsMethodForUser() throws Exception {
680         BackupManagerService backupManagerService = createService();
681         registerUser(backupManagerService, mUserOneId, mUserOneService);
682         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
683 
684         backupManagerService.setBackupEnabled(mUserOneId, true);
685 
686         verify(mUserOneService).setBackupEnabled(true);
687     }
688 
689     /** Test that the backup service does not route methods for non-registered users. */
690     @Test
testSetBackupEnabled_onUnknownUser_doesNotPropagateCall()691     public void testSetBackupEnabled_onUnknownUser_doesNotPropagateCall() throws Exception {
692         BackupManagerService backupManagerService = createService();
693         registerUser(backupManagerService, mUserOneId, mUserOneService);
694         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
695 
696         backupManagerService.setBackupEnabled(mUserTwoId, true);
697 
698         verify(mUserOneService, never()).setBackupEnabled(true);
699     }
700 
701     /** Test that the backup service routes methods correctly to the user that requests it. */
702     @Test
testSetAutoRestore_onRegisteredUser_callsMethodForUser()703     public void testSetAutoRestore_onRegisteredUser_callsMethodForUser() throws Exception {
704         BackupManagerService backupManagerService = createService();
705         registerUser(backupManagerService, mUserOneId, mUserOneService);
706         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
707 
708         backupManagerService.setAutoRestore(mUserOneId, true);
709 
710         verify(mUserOneService).setAutoRestore(true);
711     }
712 
713     /** Test that the backup service does not route methods for non-registered users. */
714     @Test
testSetAutoRestore_onUnknownUser_doesNotPropagateCall()715     public void testSetAutoRestore_onUnknownUser_doesNotPropagateCall() throws Exception {
716         BackupManagerService backupManagerService = createService();
717         registerUser(backupManagerService, mUserOneId, mUserOneService);
718         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
719 
720         backupManagerService.setAutoRestore(mUserTwoId, true);
721 
722         verify(mUserOneService, never()).setAutoRestore(true);
723     }
724 
725     /** Test that the backup service routes methods correctly to the user that requests it. */
726     @Test
testIsBackupEnabled_onRegisteredUser_callsMethodForUser()727     public void testIsBackupEnabled_onRegisteredUser_callsMethodForUser() throws Exception {
728         BackupManagerService backupManagerService = createService();
729         registerUser(backupManagerService, mUserOneId, mUserOneService);
730         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
731 
732         backupManagerService.isBackupEnabled(mUserOneId);
733 
734         verify(mUserOneService).isBackupEnabled();
735     }
736 
737     /** Test that the backup service does not route methods for non-registered users. */
738     @Test
testIsBackupEnabled_onUnknownUser_doesNotPropagateCall()739     public void testIsBackupEnabled_onUnknownUser_doesNotPropagateCall() throws Exception {
740         BackupManagerService backupManagerService = createService();
741         registerUser(backupManagerService, mUserOneId, mUserOneService);
742         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
743 
744         backupManagerService.isBackupEnabled(mUserTwoId);
745 
746         verify(mUserOneService, never()).isBackupEnabled();
747     }
748 
749     // ---------------------------------------------
750     // Backup tests
751     // ---------------------------------------------
752 
753     /** Test that the backup service routes methods correctly to the user that requests it. */
754     @Test
testIsAppEligibleForBackup_onRegisteredUser_callsMethodForUser()755     public void testIsAppEligibleForBackup_onRegisteredUser_callsMethodForUser() throws Exception {
756         BackupManagerService backupManagerService = createService();
757         registerUser(backupManagerService, mUserOneId, mUserOneService);
758         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
759 
760         backupManagerService.isAppEligibleForBackup(mUserOneId, TEST_PACKAGE);
761 
762         verify(mUserOneService).isAppEligibleForBackup(TEST_PACKAGE);
763     }
764 
765     /** Test that the backup service does not route methods for non-registered users. */
766     @Test
testIsAppEligibleForBackup_onUnknownUser_doesNotPropagateCall()767     public void testIsAppEligibleForBackup_onUnknownUser_doesNotPropagateCall() throws Exception {
768         BackupManagerService backupManagerService = createService();
769         registerUser(backupManagerService, mUserOneId, mUserOneService);
770         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
771 
772         backupManagerService.isAppEligibleForBackup(mUserTwoId, TEST_PACKAGE);
773 
774         verify(mUserOneService, never()).isAppEligibleForBackup(TEST_PACKAGE);
775     }
776 
777     /** Test that the backup service routes methods correctly to the user that requests it. */
778     @Test
testFilterAppsEligibleForBackup_onRegisteredUser_callsMethodForUser()779     public void testFilterAppsEligibleForBackup_onRegisteredUser_callsMethodForUser()
780             throws Exception {
781         BackupManagerService backupManagerService = createService();
782         registerUser(backupManagerService, mUserOneId, mUserOneService);
783         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
784         String[] packages = {TEST_PACKAGE};
785 
786         backupManagerService.filterAppsEligibleForBackup(mUserOneId, packages);
787 
788         verify(mUserOneService).filterAppsEligibleForBackup(packages);
789     }
790 
791     /** Test that the backup service does not route methods for non-registered users. */
792     @Test
testFilterAppsEligibleForBackup_onUnknownUser_doesNotPropagateCall()793     public void testFilterAppsEligibleForBackup_onUnknownUser_doesNotPropagateCall()
794             throws Exception {
795         BackupManagerService backupManagerService = createService();
796         registerUser(backupManagerService, mUserOneId, mUserOneService);
797         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
798         String[] packages = {TEST_PACKAGE};
799 
800         backupManagerService.filterAppsEligibleForBackup(mUserTwoId, packages);
801 
802         verify(mUserOneService, never()).filterAppsEligibleForBackup(packages);
803     }
804 
805     /**
806      * Test verifying that {@link BackupManagerService#backupNow(int)} throws a {@link
807      * SecurityException} if the caller does not have INTERACT_ACROSS_USERS_FULL permission.
808      */
809     @Test
testBackupNow_withoutPermission_throwsSecurityExceptionForNonCallingUser()810     public void testBackupNow_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
811         BackupManagerService backupManagerService = createService();
812         registerUser(backupManagerService, mUserOneId, mUserOneService);
813         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
814 
815         expectThrows(SecurityException.class, () -> backupManagerService.backupNow(mUserTwoId));
816     }
817 
818     /**
819      * Test that the backup service does not throw a {@link SecurityException} if the caller has
820      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
821      */
822     @Test
testBackupNow_withPermission_propagatesForNonCallingUser()823     public void testBackupNow_withPermission_propagatesForNonCallingUser() {
824         BackupManagerService backupManagerService = createService();
825         registerUser(backupManagerService, mUserOneId, mUserOneService);
826         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
827 
828         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ true);
829 
830         backupManagerService.backupNow(mUserTwoId);
831 
832         verify(mUserTwoService).backupNow();
833     }
834 
835     /** Test that the backup service routes methods correctly to the user that requests it. */
836     @Test
testBackupNow_onRegisteredUser_callsMethodForUser()837     public void testBackupNow_onRegisteredUser_callsMethodForUser() throws Exception {
838         BackupManagerService backupManagerService = createService();
839         registerUser(backupManagerService, mUserOneId, mUserOneService);
840         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
841 
842         backupManagerService.backupNow(mUserOneId);
843 
844         verify(mUserOneService).backupNow();
845     }
846 
847     /** Test that the backup service does not route methods for non-registered users. */
848     @Test
testBackupNow_onUnknownUser_doesNotPropagateCall()849     public void testBackupNow_onUnknownUser_doesNotPropagateCall() throws Exception {
850         BackupManagerService backupManagerService = createService();
851         registerUser(backupManagerService, mUserOneId, mUserOneService);
852         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
853 
854         backupManagerService.backupNow(mUserTwoId);
855 
856         verify(mUserOneService, never()).backupNow();
857     }
858 
859     /**
860      * Test that the backup services throws a {@link SecurityException} if the caller does not have
861      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
862      */
863     @Test
testRequestBackup_withoutPermission_throwsSecurityExceptionForNonCallingUser()864     public void testRequestBackup_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
865         BackupManagerService backupManagerService = createService();
866         registerUser(backupManagerService, mUserOneId, mUserOneService);
867         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
868         String[] packages = {TEST_PACKAGE};
869         IBackupObserver observer = mock(IBackupObserver.class);
870         IBackupManagerMonitor monitor = mock(IBackupManagerMonitor.class);
871 
872         expectThrows(
873                 SecurityException.class,
874                 () ->
875                         backupManagerService.requestBackup(
876                                 mUserTwoId, packages, observer, monitor, 0));
877     }
878 
879     /**
880      * Test that the backup service does not throw a {@link SecurityException} if the caller has
881      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
882      */
883     @Test
testRequestBackup_withPermission_propagatesForNonCallingUser()884     public void testRequestBackup_withPermission_propagatesForNonCallingUser() {
885         BackupManagerService backupManagerService = createService();
886         registerUser(backupManagerService, mUserOneId, mUserOneService);
887         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
888 
889         String[] packages = {TEST_PACKAGE};
890         IBackupObserver observer = mock(IBackupObserver.class);
891         IBackupManagerMonitor monitor = mock(IBackupManagerMonitor.class);
892         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ true);
893 
894         backupManagerService.requestBackup(mUserTwoId, packages, observer, monitor, /* flags */ 0);
895 
896         verify(mUserTwoService).requestBackup(packages, observer, monitor, /* flags */ 0);
897     }
898 
899     /** Test that the backup service routes methods correctly to the user that requests it. */
900     @Test
testRequestBackup_onRegisteredUser_callsMethodForUser()901     public void testRequestBackup_onRegisteredUser_callsMethodForUser() throws Exception {
902         BackupManagerService backupManagerService = createService();
903         registerUser(backupManagerService, mUserOneId, mUserOneService);
904         String[] packages = {TEST_PACKAGE};
905         IBackupObserver observer = mock(IBackupObserver.class);
906         IBackupManagerMonitor monitor = mock(IBackupManagerMonitor.class);
907         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
908 
909         backupManagerService.requestBackup(mUserOneId, packages, observer, monitor, /* flags */ 0);
910 
911         verify(mUserOneService).requestBackup(packages, observer, monitor, /* flags */ 0);
912     }
913 
914     /** Test that the backup service routes methods correctly to the user that requests it. */
915     @Test
testRequestBackup_onUnknownUser_doesNotPropagateCall()916     public void testRequestBackup_onUnknownUser_doesNotPropagateCall() throws Exception {
917         BackupManagerService backupManagerService = createService();
918         registerUser(backupManagerService, mUserOneId, mUserOneService);
919         String[] packages = {TEST_PACKAGE};
920         IBackupObserver observer = mock(IBackupObserver.class);
921         IBackupManagerMonitor monitor = mock(IBackupManagerMonitor.class);
922         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
923 
924         backupManagerService.requestBackup(mUserTwoId, packages, observer, monitor, /* flags */ 0);
925 
926         verify(mUserOneService, never()).requestBackup(packages, observer, monitor, /* flags */ 0);
927     }
928 
929     /**
930      * Test verifying that {@link BackupManagerService#cancelBackups(int)} throws a {@link
931      * SecurityException} if the caller does not have INTERACT_ACROSS_USERS_FULL permission.
932      */
933     @Test
testCancelBackups_withoutPermission_throwsSecurityExceptionForNonCallingUser()934     public void testCancelBackups_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
935         BackupManagerService backupManagerService = createService();
936         registerUser(backupManagerService, mUserOneId, mUserOneService);
937         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
938 
939         expectThrows(SecurityException.class, () -> backupManagerService.cancelBackups(mUserTwoId));
940     }
941 
942     /**
943      * Test that the backup service does not throw a {@link SecurityException} if the caller has
944      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
945      */
946     @Test
testCancelBackups_withPermission_propagatesForNonCallingUser()947     public void testCancelBackups_withPermission_propagatesForNonCallingUser() {
948         BackupManagerService backupManagerService = createService();
949         registerUser(backupManagerService, mUserOneId, mUserOneService);
950         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
951         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ true);
952 
953         backupManagerService.cancelBackups(mUserTwoId);
954 
955         verify(mUserTwoService).cancelBackups();
956     }
957 
958     /** Test that the backup service routes methods correctly to the user that requests it. */
959     @Test
testCancelBackups_onRegisteredUser_callsMethodForUser()960     public void testCancelBackups_onRegisteredUser_callsMethodForUser() throws Exception {
961         BackupManagerService backupManagerService = createService();
962         registerUser(backupManagerService, mUserOneId, mUserOneService);
963         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
964 
965         backupManagerService.cancelBackups(mUserOneId);
966 
967         verify(mUserOneService).cancelBackups();
968     }
969 
970     /** Test that the backup service does not route methods for non-registered users. */
971     @Test
testCancelBackups_onUnknownUser_doesNotPropagateCall()972     public void testCancelBackups_onUnknownUser_doesNotPropagateCall() throws Exception {
973         BackupManagerService backupManagerService = createService();
974         registerUser(backupManagerService, mUserOneId, mUserOneService);
975         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
976 
977         backupManagerService.cancelBackups(mUserTwoId);
978 
979         verify(mUserOneService, never()).cancelBackups();
980     }
981 
982     /** Test that the backup service routes methods correctly to the user that requests it. */
983     @Test
testBeginFullBackup_onRegisteredUser_callsMethodForUser()984     public void testBeginFullBackup_onRegisteredUser_callsMethodForUser() throws Exception {
985         BackupManagerService backupManagerService = createService();
986         registerUser(backupManagerService, UserHandle.USER_SYSTEM, mUserOneService);
987         FullBackupJob job = new FullBackupJob();
988 
989         backupManagerService.beginFullBackup(UserHandle.USER_SYSTEM, job);
990 
991         verify(mUserOneService).beginFullBackup(job);
992     }
993 
994     /** Test that the backup service does not route methods for non-registered users. */
995     @Test
testBeginFullBackup_onUnknownUser_doesNotPropagateCall()996     public void testBeginFullBackup_onUnknownUser_doesNotPropagateCall() throws Exception {
997         BackupManagerService backupManagerService = createService();
998         FullBackupJob job = new FullBackupJob();
999 
1000         backupManagerService.beginFullBackup(UserHandle.USER_SYSTEM, job);
1001 
1002         verify(mUserOneService, never()).beginFullBackup(job);
1003     }
1004 
1005     /** Test that the backup service routes methods correctly to the user that requests it. */
1006     @Test
testEndFullBackup_onRegisteredUser_callsMethodForUser()1007     public void testEndFullBackup_onRegisteredUser_callsMethodForUser() throws Exception {
1008         BackupManagerService backupManagerService = createService();
1009         registerUser(backupManagerService, UserHandle.USER_SYSTEM, mUserOneService);
1010 
1011         backupManagerService.endFullBackup(UserHandle.USER_SYSTEM);
1012 
1013         verify(mUserOneService).endFullBackup();
1014     }
1015 
1016     /** Test that the backup service does not route methods for non-registered users. */
1017     @Test
testEndFullBackup_onUnknownUser_doesNotPropagateCall()1018     public void testEndFullBackup_onUnknownUser_doesNotPropagateCall() throws Exception {
1019         BackupManagerService backupManagerService = createService();
1020 
1021         backupManagerService.endFullBackup(UserHandle.USER_SYSTEM);
1022 
1023         verify(mUserOneService, never()).endFullBackup();
1024     }
1025 
1026     /** Test that the backup service routes methods correctly to the user that requests it. */
1027     @Test
testFullTransportBackup_onRegisteredUser_callsMethodForUser()1028     public void testFullTransportBackup_onRegisteredUser_callsMethodForUser() throws Exception {
1029         BackupManagerService backupManagerService = createService();
1030         registerUser(backupManagerService, mUserOneId, mUserOneService);
1031         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1032         String[] packages = {TEST_PACKAGE};
1033 
1034         backupManagerService.fullTransportBackup(mUserOneId, packages);
1035 
1036         verify(mUserOneService).fullTransportBackup(packages);
1037     }
1038 
1039     /** Test that the backup service does not route methods for non-registered users. */
1040     @Test
testFullTransportBackup_onUnknownUser_doesNotPropagateCall()1041     public void testFullTransportBackup_onUnknownUser_doesNotPropagateCall() throws Exception {
1042         BackupManagerService backupManagerService = createService();
1043         registerUser(backupManagerService, mUserOneId, mUserOneService);
1044         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1045         String[] packages = {TEST_PACKAGE};
1046 
1047         backupManagerService.fullTransportBackup(mUserTwoId, packages);
1048 
1049         verify(mUserOneService, never()).fullTransportBackup(packages);
1050     }
1051 
1052     // ---------------------------------------------
1053     // Restore tests
1054     // ---------------------------------------------
1055 
1056     /** Test that the backup service routes methods correctly to the user that requests it. */
1057     @Test
testRestoreAtInstall_onRegisteredUser_callsMethodForUser()1058     public void testRestoreAtInstall_onRegisteredUser_callsMethodForUser() throws Exception {
1059         BackupManagerService backupManagerService = createService();
1060         registerUser(backupManagerService, mUserOneId, mUserOneService);
1061         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1062 
1063         backupManagerService.restoreAtInstall(mUserOneId, TEST_PACKAGE, /* token */ 0);
1064 
1065         verify(mUserOneService).restoreAtInstall(TEST_PACKAGE, /* token */ 0);
1066     }
1067 
1068     /** Test that the backup service does not route methods for non-registered users. */
1069     @Test
testRestoreAtInstall_onUnknownUser_doesNotPropagateCall()1070     public void testRestoreAtInstall_onUnknownUser_doesNotPropagateCall() throws Exception {
1071         BackupManagerService backupManagerService = createService();
1072         registerUser(backupManagerService, mUserOneId, mUserOneService);
1073         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1074 
1075         backupManagerService.restoreAtInstall(mUserTwoId, TEST_PACKAGE, /* token */ 0);
1076 
1077         verify(mUserOneService, never()).restoreAtInstall(TEST_PACKAGE, /* token */ 0);
1078     }
1079 
1080     /** Test that the backup service routes methods correctly to the user that requests it. */
1081     @Test
testBeginRestoreSession_onRegisteredUser_callsMethodForUser()1082     public void testBeginRestoreSession_onRegisteredUser_callsMethodForUser() throws Exception {
1083         BackupManagerService backupManagerService = createService();
1084         registerUser(backupManagerService, mUserOneId, mUserOneService);
1085         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1086 
1087         backupManagerService.beginRestoreSession(mUserOneId, TEST_PACKAGE, TEST_TRANSPORT);
1088 
1089         verify(mUserOneService).beginRestoreSession(TEST_PACKAGE, TEST_TRANSPORT);
1090     }
1091 
1092     /** Test that the backup service does not route methods for non-registered users. */
1093     @Test
testBeginRestoreSession_onUnknownUser_doesNotPropagateCall()1094     public void testBeginRestoreSession_onUnknownUser_doesNotPropagateCall() throws Exception {
1095         BackupManagerService backupManagerService = createService();
1096         registerUser(backupManagerService, mUserOneId, mUserOneService);
1097         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1098 
1099         backupManagerService.beginRestoreSession(mUserTwoId, TEST_PACKAGE, TEST_TRANSPORT);
1100 
1101         verify(mUserOneService, never()).beginRestoreSession(TEST_PACKAGE, TEST_TRANSPORT);
1102     }
1103 
1104     /** Test that the backup service routes methods correctly to the user that requests it. */
1105     @Test
testGetAvailableRestoreToken_onRegisteredUser_callsMethodForUser()1106     public void testGetAvailableRestoreToken_onRegisteredUser_callsMethodForUser()
1107             throws Exception {
1108         BackupManagerService backupManagerService = createService();
1109         registerUser(backupManagerService, mUserOneId, mUserOneService);
1110         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1111 
1112         backupManagerService.getAvailableRestoreToken(mUserOneId, TEST_PACKAGE);
1113 
1114         verify(mUserOneService).getAvailableRestoreToken(TEST_PACKAGE);
1115     }
1116 
1117     /** Test that the backup service does not route methods for non-registered users. */
1118     @Test
testGetAvailableRestoreToken_onUnknownUser_doesNotPropagateCall()1119     public void testGetAvailableRestoreToken_onUnknownUser_doesNotPropagateCall() throws Exception {
1120         BackupManagerService backupManagerService = createService();
1121         registerUser(backupManagerService, mUserOneId, mUserOneService);
1122         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1123 
1124         backupManagerService.getAvailableRestoreToken(mUserTwoId, TEST_PACKAGE);
1125 
1126         verify(mUserOneService, never()).getAvailableRestoreToken(TEST_PACKAGE);
1127     }
1128 
1129     // ---------------------------------------------
1130     // Adb backup/restore tests
1131     // ---------------------------------------------
1132 
1133     /** Test that the backup service routes methods correctly to the user that requests it. */
1134     @Test
testSetBackupPassword_onRegisteredUser_callsMethodForUser()1135     public void testSetBackupPassword_onRegisteredUser_callsMethodForUser() throws Exception {
1136         BackupManagerService backupManagerService = createService();
1137         registerUser(backupManagerService, UserHandle.USER_SYSTEM, mUserOneService);
1138         ShadowBinder.setCallingUserHandle(UserHandle.of(UserHandle.USER_SYSTEM));
1139 
1140         backupManagerService.setBackupPassword("currentPassword", "newPassword");
1141 
1142         verify(mUserOneService).setBackupPassword("currentPassword", "newPassword");
1143     }
1144 
1145     /** Test that the backup service does not route methods for non-registered users. */
1146     @Test
testSetBackupPassword_onUnknownUser_doesNotPropagateCall()1147     public void testSetBackupPassword_onUnknownUser_doesNotPropagateCall() throws Exception {
1148         BackupManagerService backupManagerService = createService();
1149 
1150         backupManagerService.setBackupPassword("currentPassword", "newPassword");
1151 
1152         verify(mUserOneService, never()).setBackupPassword("currentPassword", "newPassword");
1153     }
1154 
1155     /** Test that the backup service routes methods correctly to the user that requests it. */
1156     @Test
testHasBackupPassword_onRegisteredUser_callsMethodForUser()1157     public void testHasBackupPassword_onRegisteredUser_callsMethodForUser() throws Exception {
1158         BackupManagerService backupManagerService = createService();
1159         registerUser(backupManagerService, UserHandle.USER_SYSTEM, mUserOneService);
1160         ShadowBinder.setCallingUserHandle(UserHandle.of(UserHandle.USER_SYSTEM));
1161 
1162         backupManagerService.hasBackupPassword();
1163 
1164         verify(mUserOneService).hasBackupPassword();
1165     }
1166 
1167     /** Test that the backup service does not route methods for non-registered users. */
1168     @Test
testHasBackupPassword_onUnknownUser_doesNotPropagateCall()1169     public void testHasBackupPassword_onUnknownUser_doesNotPropagateCall() throws Exception {
1170         BackupManagerService backupManagerService = createService();
1171 
1172         backupManagerService.hasBackupPassword();
1173 
1174         verify(mUserOneService, never()).hasBackupPassword();
1175     }
1176 
1177     /**
1178      * Test that the backup services throws a {@link SecurityException} if the caller does not have
1179      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
1180      */
1181     @Test
testAdbBackup_withoutPermission_throwsSecurityExceptionForNonCallingUser()1182     public void testAdbBackup_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
1183         BackupManagerService backupManagerService = createSystemRegisteredService();
1184         registerUser(backupManagerService, mUserOneId, mUserOneService);
1185         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
1186         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1187 
1188         expectThrows(
1189                 SecurityException.class,
1190                 () ->
1191                         backupManagerService.adbBackup(
1192                                 mUserTwoId,
1193                                 /* parcelFileDescriptor*/ null,
1194                                 /* includeApks */ true,
1195                                 /* includeObbs */ true,
1196                                 /* includeShared */ true,
1197                                 /* doWidgets */ true,
1198                                 /* doAllApps */ true,
1199                                 /* includeSystem */ true,
1200                                 /* doCompress */ true,
1201                                 /* doKeyValue */ true,
1202                                 null));
1203     }
1204 
1205     /**
1206      * Test that the backup service does not throw a {@link SecurityException} if the caller has
1207      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
1208      */
1209     @Test
testAdbBackup_withPermission_propagatesForNonCallingUser()1210     public void testAdbBackup_withPermission_propagatesForNonCallingUser() throws Exception {
1211         BackupManagerService backupManagerService = createSystemRegisteredService();
1212         registerUser(backupManagerService, mUserOneId, mUserOneService);
1213         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
1214 
1215         ParcelFileDescriptor parcelFileDescriptor = getFileDescriptorForAdbTest();
1216         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ true);
1217 
1218         backupManagerService.adbBackup(
1219                 mUserTwoId,
1220                 parcelFileDescriptor,
1221                 /* includeApks */ true,
1222                 /* includeObbs */ true,
1223                 /* includeShared */ true,
1224                 /* doWidgets */ true,
1225                 /* doAllApps */ true,
1226                 /* includeSystem */ true,
1227                 /* doCompress */ true,
1228                 /* doKeyValue */ true,
1229                 ADB_TEST_PACKAGES);
1230 
1231         verify(mUserTwoService)
1232                 .adbBackup(
1233                         parcelFileDescriptor,
1234                         /* includeApks */ true,
1235                         /* includeObbs */ true,
1236                         /* includeShared */ true,
1237                         /* doWidgets */ true,
1238                         /* doAllApps */ true,
1239                         /* includeSystem */ true,
1240                         /* doCompress */ true,
1241                         /* doKeyValue */ true,
1242                         ADB_TEST_PACKAGES);
1243     }
1244 
1245     /** Test that the backup service routes methods correctly to the user that requests it. */
1246     @Test
testAdbBackup_onRegisteredUser_callsMethodForUser()1247     public void testAdbBackup_onRegisteredUser_callsMethodForUser() throws Exception {
1248         BackupManagerService backupManagerService = createSystemRegisteredService();
1249         registerUser(backupManagerService, mUserOneId, mUserOneService);
1250         ParcelFileDescriptor parcelFileDescriptor = getFileDescriptorForAdbTest();
1251         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1252 
1253         backupManagerService.adbBackup(
1254                 mUserOneId,
1255                 parcelFileDescriptor,
1256                 /* includeApks */ true,
1257                 /* includeObbs */ true,
1258                 /* includeShared */ true,
1259                 /* doWidgets */ true,
1260                 /* doAllApps */ true,
1261                 /* includeSystem */ true,
1262                 /* doCompress */ true,
1263                 /* doKeyValue */ true,
1264                 ADB_TEST_PACKAGES);
1265 
1266         verify(mUserOneService)
1267                 .adbBackup(
1268                         parcelFileDescriptor,
1269                         /* includeApks */ true,
1270                         /* includeObbs */ true,
1271                         /* includeShared */ true,
1272                         /* doWidgets */ true,
1273                         /* doAllApps */ true,
1274                         /* includeSystem */ true,
1275                         /* doCompress */ true,
1276                         /* doKeyValue */ true,
1277                         ADB_TEST_PACKAGES);
1278     }
1279 
1280     /** Test that the backup service does not route methods for non-registered users. */
1281     @Test
testAdbBackup_onUnknownUser_doesNotPropagateCall()1282     public void testAdbBackup_onUnknownUser_doesNotPropagateCall() throws Exception {
1283         BackupManagerService backupManagerService = createSystemRegisteredService();
1284         registerUser(backupManagerService, mUserOneId, mUserOneService);
1285         ParcelFileDescriptor parcelFileDescriptor = getFileDescriptorForAdbTest();
1286         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1287 
1288         backupManagerService.adbBackup(
1289                 mUserTwoId,
1290                 parcelFileDescriptor,
1291                 /* includeApks */ true,
1292                 /* includeObbs */ true,
1293                 /* includeShared */ true,
1294                 /* doWidgets */ true,
1295                 /* doAllApps */ true,
1296                 /* includeSystem */ true,
1297                 /* doCompress */ true,
1298                 /* doKeyValue */ true,
1299                 ADB_TEST_PACKAGES);
1300 
1301         verify(mUserOneService, never())
1302                 .adbBackup(
1303                         parcelFileDescriptor,
1304                         /* includeApks */ true,
1305                         /* includeObbs */ true,
1306                         /* includeShared */ true,
1307                         /* doWidgets */ true,
1308                         /* doAllApps */ true,
1309                         /* includeSystem */ true,
1310                         /* doCompress */ true,
1311                         /* doKeyValue */ true,
1312                         ADB_TEST_PACKAGES);
1313     }
1314 
1315     /**
1316      * Test that the backup services throws a {@link SecurityException} if the caller does not have
1317      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
1318      */
1319     @Test
testAdbRestore_withoutPermission_throwsSecurityExceptionForNonCallingUser()1320     public void testAdbRestore_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
1321         BackupManagerService backupManagerService = createSystemRegisteredService();
1322         registerUser(backupManagerService, mUserOneId, mUserOneService);
1323         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
1324         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1325 
1326         expectThrows(
1327                 SecurityException.class, () -> backupManagerService.adbRestore(mUserTwoId, null));
1328     }
1329 
1330     /**
1331      * Test that the backup service does not throw a {@link SecurityException} if the caller has
1332      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
1333      */
1334     @Test
testAdbRestore_withPermission_propagatesForNonCallingUser()1335     public void testAdbRestore_withPermission_propagatesForNonCallingUser() throws Exception {
1336         BackupManagerService backupManagerService = createSystemRegisteredService();
1337         registerUser(backupManagerService, mUserOneId, mUserOneService);
1338         registerUser(backupManagerService, mUserTwoId, mUserTwoService);
1339         ParcelFileDescriptor parcelFileDescriptor = getFileDescriptorForAdbTest();
1340         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ true);
1341 
1342         backupManagerService.adbRestore(mUserTwoId, parcelFileDescriptor);
1343 
1344         verify(mUserTwoService).adbRestore(parcelFileDescriptor);
1345     }
1346 
1347     /** Test that the backup service routes methods correctly to the user that requests it. */
1348     @Test
testAdbRestore_onRegisteredUser_callsMethodForUser()1349     public void testAdbRestore_onRegisteredUser_callsMethodForUser() throws Exception {
1350         BackupManagerService backupManagerService = createSystemRegisteredService();
1351         registerUser(backupManagerService, mUserOneId, mUserOneService);
1352         ParcelFileDescriptor parcelFileDescriptor = getFileDescriptorForAdbTest();
1353         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1354 
1355         backupManagerService.adbRestore(mUserOneId, parcelFileDescriptor);
1356 
1357         verify(mUserOneService).adbRestore(parcelFileDescriptor);
1358     }
1359 
1360     /** Test that the backup service does not route methods for non-registered users. */
1361     @Test
testAdbRestore_onUnknownUser_doesNotPropagateCall()1362     public void testAdbRestore_onUnknownUser_doesNotPropagateCall() throws Exception {
1363         BackupManagerService backupManagerService = createSystemRegisteredService();
1364         registerUser(backupManagerService, mUserOneId, mUserOneService);
1365         ParcelFileDescriptor parcelFileDescriptor = getFileDescriptorForAdbTest();
1366         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1367 
1368         backupManagerService.adbRestore(mUserTwoId, parcelFileDescriptor);
1369 
1370         verify(mUserOneService, never()).adbRestore(parcelFileDescriptor);
1371     }
1372 
getFileDescriptorForAdbTest()1373     private ParcelFileDescriptor getFileDescriptorForAdbTest() throws Exception {
1374         File testFile = new File(mContext.getFilesDir(), "test");
1375         testFile.createNewFile();
1376         return ParcelFileDescriptor.open(testFile, ParcelFileDescriptor.MODE_READ_WRITE);
1377     }
1378 
1379     /** Test that the backup service routes methods correctly to the user that requests it. */
1380     @Test
testAcknowledgeAdbBackupOrRestore_onRegisteredUser_callsMethodForUser()1381     public void testAcknowledgeAdbBackupOrRestore_onRegisteredUser_callsMethodForUser()
1382             throws Exception {
1383         BackupManagerService backupManagerService = createService();
1384         registerUser(backupManagerService, mUserOneId, mUserOneService);
1385         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1386         IFullBackupRestoreObserver observer = mock(IFullBackupRestoreObserver.class);
1387 
1388         backupManagerService.acknowledgeAdbBackupOrRestore(
1389                 mUserOneId,
1390                 /* token */ 0,
1391                 /* allow */ true,
1392                 "currentPassword",
1393                 "encryptionPassword",
1394                 observer);
1395 
1396         verify(mUserOneService)
1397                 .acknowledgeAdbBackupOrRestore(
1398                         /* token */ 0,
1399                         /* allow */ true,
1400                         "currentPassword",
1401                         "encryptionPassword",
1402                         observer);
1403     }
1404 
1405     /** Test that the backup service does not route methods for non-registered users. */
1406     @Test
testAcknowledgeAdbBackupOrRestore_onUnknownUser_doesNotPropagateCall()1407     public void testAcknowledgeAdbBackupOrRestore_onUnknownUser_doesNotPropagateCall()
1408             throws Exception {
1409         BackupManagerService backupManagerService = createService();
1410         registerUser(backupManagerService, mUserOneId, mUserOneService);
1411         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1412         IFullBackupRestoreObserver observer = mock(IFullBackupRestoreObserver.class);
1413 
1414         backupManagerService.acknowledgeAdbBackupOrRestore(
1415                 mUserTwoId,
1416                 /* token */ 0,
1417                 /* allow */ true,
1418                 "currentPassword",
1419                 "encryptionPassword",
1420                 observer);
1421 
1422         verify(mUserOneService, never())
1423                 .acknowledgeAdbBackupOrRestore(
1424                         /* token */ 0,
1425                         /* allow */ true,
1426                         "currentPassword",
1427                         "encryptionPassword",
1428                         observer);
1429     }
1430 
1431     // ---------------------------------------------
1432     //  Service tests
1433     // ---------------------------------------------
1434 
1435     /** Test that the backup service routes methods correctly to the user that requests it. */
1436     @Test
testDump_onRegisteredUser_callsMethodForUser()1437     public void testDump_onRegisteredUser_callsMethodForUser() throws Exception {
1438         grantDumpPermissions();
1439         BackupManagerService backupManagerService = createSystemRegisteredService();
1440         File testFile = createTestFile();
1441         FileDescriptor fileDescriptor = new FileDescriptor();
1442         PrintWriter printWriter = new PrintWriter(testFile);
1443         String[] args = {"1", "2"};
1444         ShadowBinder.setCallingUserHandle(UserHandle.of(UserHandle.USER_SYSTEM));
1445 
1446         backupManagerService.dump(fileDescriptor, printWriter, args);
1447 
1448         verify(mUserSystemService).dump(fileDescriptor, printWriter, args);
1449     }
1450 
1451     /** Test that the backup service does not route methods for non-registered users. */
1452     @Test
testDump_onUnknownUser_doesNotPropagateCall()1453     public void testDump_onUnknownUser_doesNotPropagateCall() throws Exception {
1454         grantDumpPermissions();
1455         BackupManagerService backupManagerService = createService();
1456         File testFile = createTestFile();
1457         FileDescriptor fileDescriptor = new FileDescriptor();
1458         PrintWriter printWriter = new PrintWriter(testFile);
1459         String[] args = {"1", "2"};
1460 
1461         backupManagerService.dump(fileDescriptor, printWriter, args);
1462 
1463         verify(mUserOneService, never()).dump(fileDescriptor, printWriter, args);
1464     }
1465 
1466     /** Test that 'dumpsys backup users' dumps the list of users registered in backup service*/
1467     @Test
testDump_users_dumpsListOfRegisteredUsers()1468     public void testDump_users_dumpsListOfRegisteredUsers() {
1469         grantDumpPermissions();
1470         BackupManagerService backupManagerService = createSystemRegisteredService();
1471         registerUser(backupManagerService, mUserOneId, mUserOneService);
1472         StringWriter out = new StringWriter();
1473         PrintWriter writer = new PrintWriter(out);
1474         String[] args = {"users"};
1475 
1476         backupManagerService.dump(null, writer, args);
1477 
1478         writer.flush();
1479         assertEquals(
1480                 String.format("%s %d %d\n", BackupManagerService.DUMP_RUNNING_USERS_MESSAGE,
1481                         UserHandle.USER_SYSTEM, mUserOneId),
1482                 out.toString());
1483     }
1484 
createTestFile()1485     private File createTestFile() throws IOException {
1486         File testFile = new File(mContext.getFilesDir(), "test");
1487         testFile.createNewFile();
1488         return testFile;
1489     }
1490 
grantDumpPermissions()1491     private void grantDumpPermissions() {
1492         mShadowContext.grantPermissions(DUMP);
1493         mShadowContext.grantPermissions(PACKAGE_USAGE_STATS);
1494     }
1495 
1496     /**
1497      * Test that the backup services throws a {@link SecurityException} if the caller does not have
1498      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
1499      */
1500     @Test
testGetServiceForUser_withoutPermission_throwsSecurityExceptionForNonCallingUser()1501     public void testGetServiceForUser_withoutPermission_throwsSecurityExceptionForNonCallingUser() {
1502         BackupManagerService backupManagerService = createService();
1503         registerUser(backupManagerService, mUserOneId, mUserOneService);
1504         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ false);
1505 
1506         expectThrows(
1507                 SecurityException.class,
1508                 () ->
1509                         backupManagerService.getServiceForUserIfCallerHasPermission(
1510                                 mUserOneId, "test"));
1511     }
1512 
1513     /**
1514      * Test that the backup services does not throw a {@link SecurityException} if the caller has
1515      * INTERACT_ACROSS_USERS_FULL permission and passes a different user id.
1516      */
1517     @Test
testGetServiceForUserIfCallerHasPermission_withPermission_worksForNonCallingUser()1518     public void testGetServiceForUserIfCallerHasPermission_withPermission_worksForNonCallingUser() {
1519         BackupManagerService backupManagerService = createService();
1520         registerUser(backupManagerService, mUserOneId, mUserOneService);
1521         setCallerAndGrantInteractUserPermission(mUserTwoId, /* shouldGrantPermission */ true);
1522 
1523         assertEquals(
1524                 mUserOneService,
1525                 backupManagerService.getServiceForUserIfCallerHasPermission(mUserOneId, "test"));
1526     }
1527 
1528     /**
1529      * Test that the backup services does not throw a {@link SecurityException} if the caller does
1530      * not have INTERACT_ACROSS_USERS_FULL permission and passes in the calling user id.
1531      */
1532     @Test
testGetServiceForUserIfCallerHasPermission_withoutPermission_worksForCallingUser()1533     public void testGetServiceForUserIfCallerHasPermission_withoutPermission_worksForCallingUser() {
1534         BackupManagerService backupManagerService = createService();
1535         registerUser(backupManagerService, mUserOneId, mUserOneService);
1536         setCallerAndGrantInteractUserPermission(mUserOneId, /* shouldGrantPermission */ false);
1537 
1538         assertEquals(
1539                 mUserOneService,
1540                 backupManagerService.getServiceForUserIfCallerHasPermission(mUserOneId, "test"));
1541     }
1542 
1543     /**
1544      * Test verifying that {@link BackupManagerService#MORE_DEBUG} is set to {@code false}. This is
1545      * specifically to prevent overloading the logs in production.
1546      */
1547     @Test
testMoreDebug_isFalse()1548     public void testMoreDebug_isFalse() throws Exception {
1549         boolean moreDebug = BackupManagerService.MORE_DEBUG;
1550 
1551         assertThat(moreDebug).isFalse();
1552     }
1553 
1554     /** Test that the constructor handles {@code null} parameters. */
1555     @Test
testConstructor_withNullContext_throws()1556     public void testConstructor_withNullContext_throws() throws Exception {
1557         expectThrows(
1558                 NullPointerException.class,
1559                 () ->
1560                         new BackupManagerService(
1561                                 /* context */ null,
1562                                 new SparseArray<>()));
1563     }
1564 
1565     /** Test that the constructor does not create {@link UserBackupManagerService} instances. */
1566     @Test
testConstructor_doesNotRegisterUsers()1567     public void testConstructor_doesNotRegisterUsers() throws Exception {
1568         BackupManagerService backupManagerService = createService();
1569 
1570         assertThat(backupManagerService.getUserServices().size()).isEqualTo(0);
1571     }
1572 
1573     // ---------------------------------------------
1574     //  Lifecycle tests
1575     // ---------------------------------------------
1576 
1577     /** testOnStart_publishesService */
1578     @Test
testOnStart_publishesService()1579     public void testOnStart_publishesService() {
1580         BackupManagerService backupManagerService = mock(BackupManagerService.class);
1581         BackupManagerService.Lifecycle lifecycle =
1582                 spy(new BackupManagerService.Lifecycle(mContext, backupManagerService));
1583         doNothing().when(lifecycle).publishService(anyString(), any());
1584 
1585         lifecycle.onStart();
1586 
1587         verify(lifecycle).publishService(Context.BACKUP_SERVICE, backupManagerService);
1588     }
1589 
1590     /** testOnUnlockUser_forwards */
1591     @Test
testOnUnlockUser_forwards()1592     public void testOnUnlockUser_forwards() {
1593         BackupManagerService backupManagerService = mock(BackupManagerService.class);
1594         BackupManagerService.Lifecycle lifecycle =
1595                 new BackupManagerService.Lifecycle(mContext, backupManagerService);
1596 
1597         lifecycle.onUserUnlocking(new TargetUser(new UserInfo(UserHandle.USER_SYSTEM, null, 0)));
1598 
1599         verify(backupManagerService).onUnlockUser(UserHandle.USER_SYSTEM);
1600     }
1601 
1602     /** testOnStopUser_forwards */
1603     @Test
testOnStopUser_forwards()1604     public void testOnStopUser_forwards() {
1605         BackupManagerService backupManagerService = mock(BackupManagerService.class);
1606         BackupManagerService.Lifecycle lifecycle =
1607                 new BackupManagerService.Lifecycle(mContext, backupManagerService);
1608 
1609         lifecycle.onUserStopping(new TargetUser(new UserInfo(UserHandle.USER_SYSTEM, null, 0)));
1610 
1611         verify(backupManagerService).onStopUser(UserHandle.USER_SYSTEM);
1612     }
1613 
createService()1614     private BackupManagerService createService() {
1615         return new BackupManagerService(mContext);
1616     }
1617 
createSystemRegisteredService()1618     private BackupManagerService createSystemRegisteredService() {
1619         BackupManagerService backupManagerService = createService();
1620         registerUser(backupManagerService, UserHandle.USER_SYSTEM, mUserSystemService);
1621         return backupManagerService;
1622     }
1623 
registerUser( BackupManagerService backupManagerService, int userId, UserBackupManagerService userBackupManagerService)1624     private void registerUser(
1625             BackupManagerService backupManagerService,
1626             int userId,
1627             UserBackupManagerService userBackupManagerService) {
1628         backupManagerService.setBackupServiceActive(userId, true);
1629         backupManagerService.startServiceForUser(userId, userBackupManagerService);
1630     }
1631 
createServiceAndRegisterUser( int userId, UserBackupManagerService userBackupManagerService)1632     private BackupManagerService createServiceAndRegisterUser(
1633             int userId, UserBackupManagerService userBackupManagerService) {
1634         BackupManagerService backupManagerService = createService();
1635         backupManagerService.setBackupServiceActive(userBackupManagerService.getUserId(), true);
1636         backupManagerService.startServiceForUser(userId, userBackupManagerService);
1637         return backupManagerService;
1638     }
1639 
1640     /**
1641      * Sets the calling user to {@code userId} and grants the permission INTERACT_ACROSS_USERS_FULL
1642      * to the caller if {@code shouldGrantPermission} is {@code true}, else it denies the
1643      * permission.
1644      */
setCallerAndGrantInteractUserPermission( @serIdInt int userId, boolean shouldGrantPermission)1645     private void setCallerAndGrantInteractUserPermission(
1646             @UserIdInt int userId, boolean shouldGrantPermission) {
1647         ShadowBinder.setCallingUserHandle(UserHandle.of(userId));
1648         if (shouldGrantPermission) {
1649             mShadowContext.grantPermissions(INTERACT_ACROSS_USERS_FULL);
1650         } else {
1651             mShadowContext.denyPermissions(INTERACT_ACROSS_USERS_FULL);
1652         }
1653     }
1654 }
1655