1 /*
2  * Copyright (C) 2009 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.accounts;
18 
19 import static android.database.sqlite.SQLiteDatabase.deleteDatabase;
20 
21 import static org.mockito.Matchers.any;
22 import static org.mockito.Matchers.anyBoolean;
23 import static org.mockito.Matchers.anyInt;
24 import static org.mockito.Matchers.anyString;
25 import static org.mockito.Matchers.eq;
26 import static org.mockito.Mockito.atLeast;
27 import static org.mockito.Mockito.never;
28 import static org.mockito.Mockito.nullable;
29 import static org.mockito.Mockito.verify;
30 import static org.mockito.Mockito.when;
31 
32 import android.accounts.Account;
33 import android.accounts.AccountManager;
34 import android.accounts.AccountManagerInternal;
35 import android.accounts.CantAddAccountActivity;
36 import android.accounts.IAccountManagerResponse;
37 import android.app.AppOpsManager;
38 import android.app.INotificationManager;
39 import android.app.admin.DevicePolicyManager;
40 import android.app.admin.DevicePolicyManagerInternal;
41 import android.content.BroadcastReceiver;
42 import android.content.Context;
43 import android.content.Intent;
44 import android.content.IntentFilter;
45 import android.content.ServiceConnection;
46 import android.content.pm.ActivityInfo;
47 import android.content.pm.ApplicationInfo;
48 import android.content.pm.PackageInfo;
49 import android.content.pm.PackageManager;
50 import android.content.pm.PackageManagerInternal;
51 import android.content.pm.ResolveInfo;
52 import android.content.pm.Signature;
53 import android.content.pm.UserInfo;
54 import android.database.Cursor;
55 import android.database.DatabaseErrorHandler;
56 import android.database.sqlite.SQLiteDatabase;
57 import android.os.Bundle;
58 import android.os.Handler;
59 import android.os.IBinder;
60 import android.os.Looper;
61 import android.os.RemoteException;
62 import android.os.SystemClock;
63 import android.os.UserHandle;
64 import android.os.UserManager;
65 import android.test.AndroidTestCase;
66 import android.test.mock.MockContext;
67 import android.test.suitebuilder.annotation.SmallTest;
68 import android.util.Log;
69 
70 import com.android.server.LocalServices;
71 
72 import org.mockito.ArgumentCaptor;
73 import org.mockito.Captor;
74 import org.mockito.Mock;
75 import org.mockito.MockitoAnnotations;
76 
77 import java.io.File;
78 import java.security.GeneralSecurityException;
79 import java.util.ArrayList;
80 import java.util.Arrays;
81 import java.util.Collections;
82 import java.util.Comparator;
83 import java.util.HashMap;
84 import java.util.List;
85 import java.util.concurrent.CountDownLatch;
86 import java.util.concurrent.CyclicBarrier;
87 import java.util.concurrent.ExecutorService;
88 import java.util.concurrent.Executors;
89 import java.util.concurrent.TimeUnit;
90 import java.util.concurrent.atomic.AtomicLong;
91 
92 /**
93  * Tests for {@link AccountManagerService}.
94  * <p>Run with:<pre>
95  * mmma -j40 frameworks/base/services/tests/servicestests
96  * adb install -r ${OUT}/data/app/FrameworksServicesTests/FrameworksServicesTests.apk
97  * adb shell am instrument -w -e package com.android.server.accounts \
98  * com.android.frameworks.servicestests\
99  * /androidx.test.runner.AndroidJUnitRunner
100  * </pre>
101  */
102 public class AccountManagerServiceTest extends AndroidTestCase {
103     private static final String TAG = AccountManagerServiceTest.class.getSimpleName();
104     private static final long ONE_DAY_IN_MILLISECOND = 86400000;
105 
106     @Mock private Context mMockContext;
107     @Mock private AppOpsManager mMockAppOpsManager;
108     @Mock private UserManager mMockUserManager;
109     @Mock private PackageManager mMockPackageManager;
110     @Mock private DevicePolicyManagerInternal mMockDevicePolicyManagerInternal;
111     @Mock private DevicePolicyManager mMockDevicePolicyManager;
112     @Mock private IAccountManagerResponse mMockAccountManagerResponse;
113     @Mock private IBinder mMockBinder;
114     @Mock private INotificationManager mMockNotificationManager;
115     @Mock private PackageManagerInternal mMockPackageManagerInternal;
116 
117     @Captor private ArgumentCaptor<Intent> mIntentCaptor;
118     @Captor private ArgumentCaptor<Bundle> mBundleCaptor;
119     private int mVisibleAccountsChangedBroadcasts;
120     private int mLoginAccountsChangedBroadcasts;
121     private int mAccountRemovedBroadcasts;
122 
123     private static final int LATCH_TIMEOUT_MS = 500;
124     private static final String PREN_DB = "pren.db";
125     private static final String DE_DB = "de.db";
126     private static final String CE_DB = "ce.db";
127     private PackageInfo mPackageInfo;
128     private AccountManagerService mAms;
129     private TestInjector mTestInjector;
130 
131     @Override
setUp()132     protected void setUp() throws Exception {
133         MockitoAnnotations.initMocks(this);
134 
135         when(mMockPackageManager.checkSignatures(anyInt(), anyInt()))
136                     .thenReturn(PackageManager.SIGNATURE_MATCH);
137         final UserInfo ui = new UserInfo(UserHandle.USER_SYSTEM, "user0", 0);
138         when(mMockUserManager.getUserInfo(eq(ui.id))).thenReturn(ui);
139         when(mMockContext.createPackageContextAsUser(
140                  anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext);
141         when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
142 
143         mPackageInfo = new PackageInfo();
144         mPackageInfo.signatures = new Signature[1];
145         mPackageInfo.signatures[0] = new Signature(new byte[] {'a', 'b', 'c', 'd'});
146         mPackageInfo.applicationInfo = new ApplicationInfo();
147         mPackageInfo.applicationInfo.privateFlags = ApplicationInfo.PRIVATE_FLAG_PRIVILEGED;
148         when(mMockPackageManager.getPackageInfo(anyString(), anyInt())).thenReturn(mPackageInfo);
149         when(mMockContext.getSystemService(Context.APP_OPS_SERVICE)).thenReturn(mMockAppOpsManager);
150         when(mMockContext.getSystemService(Context.USER_SERVICE)).thenReturn(mMockUserManager);
151         when(mMockContext.getSystemServiceName(AppOpsManager.class)).thenReturn(
152                 Context.APP_OPS_SERVICE);
153         when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn(
154                 PackageManager.PERMISSION_GRANTED);
155         Bundle bundle = new Bundle();
156         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
157         when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn(
158                 mMockDevicePolicyManager);
159         when(mMockAccountManagerResponse.asBinder()).thenReturn(mMockBinder);
160         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
161                 .thenReturn(true);
162         LocalServices.addService(PackageManagerInternal.class, mMockPackageManagerInternal);
163 
164         Context realTestContext = getContext();
165         MyMockContext mockContext = new MyMockContext(realTestContext, mMockContext);
166         setContext(mockContext);
167         mTestInjector = new TestInjector(realTestContext, mockContext, mMockNotificationManager);
168         mAms = new AccountManagerService(mTestInjector);
169     }
170 
171     @Override
tearDown()172     protected void tearDown() throws Exception {
173         // Let async logging tasks finish, otherwise they may crash due to db being removed
174         CountDownLatch cdl = new CountDownLatch(1);
175         mAms.mHandler.post(() -> {
176             deleteDatabase(new File(mTestInjector.getCeDatabaseName(UserHandle.USER_SYSTEM)));
177             deleteDatabase(new File(mTestInjector.getDeDatabaseName(UserHandle.USER_SYSTEM)));
178             deleteDatabase(new File(mTestInjector.getPreNDatabaseName(UserHandle.USER_SYSTEM)));
179             cdl.countDown();
180         });
181         cdl.await(1, TimeUnit.SECONDS);
182         LocalServices.removeServiceForTest(PackageManagerInternal.class);
183         super.tearDown();
184     }
185 
186     class AccountSorter implements Comparator<Account> {
compare(Account object1, Account object2)187         public int compare(Account object1, Account object2) {
188             if (object1 == object2) return 0;
189             if (object1 == null) return 1;
190             if (object2 == null) return -1;
191             int result = object1.type.compareTo(object2.type);
192             if (result != 0) return result;
193             return object1.name.compareTo(object2.name);
194         }
195     }
196 
197     @SmallTest
testCheckAddAccount()198     public void testCheckAddAccount() throws Exception {
199         unlockSystemUser();
200         Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
201         Account a21 = new Account("account2", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
202         Account a31 = new Account("account3", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
203         Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
204         Account a22 = new Account("account2", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
205         Account a32 = new Account("account3", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
206         mAms.addAccountExplicitly(a11, "p11", null);
207         mAms.addAccountExplicitly(a12, "p12", null);
208         mAms.addAccountExplicitly(a21, "p21", null);
209         mAms.addAccountExplicitly(a22, "p22", null);
210         mAms.addAccountExplicitly(a31, "p31", null);
211         mAms.addAccountExplicitly(a32, "p32", null);
212 
213         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
214         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
215         Account[] accounts = mAms.getAccounts(null, mContext.getOpPackageName());
216         Arrays.sort(accounts, new AccountSorter());
217         assertEquals(6, accounts.length);
218         assertEquals(a11, accounts[0]);
219         assertEquals(a21, accounts[1]);
220         assertEquals(a31, accounts[2]);
221         assertEquals(a12, accounts[3]);
222         assertEquals(a22, accounts[4]);
223         assertEquals(a32, accounts[5]);
224 
225         accounts = mAms.getAccounts(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
226                 mContext.getOpPackageName());
227         Arrays.sort(accounts, new AccountSorter());
228         assertEquals(3, accounts.length);
229         assertEquals(a11, accounts[0]);
230         assertEquals(a21, accounts[1]);
231         assertEquals(a31, accounts[2]);
232 
233         mAms.removeAccountInternal(a21);
234 
235         accounts = mAms.getAccounts(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
236                 mContext.getOpPackageName());
237         Arrays.sort(accounts, new AccountSorter());
238         assertEquals(2, accounts.length);
239         assertEquals(a11, accounts[0]);
240         assertEquals(a31, accounts[1]);
241     }
242 
243     @SmallTest
testPasswords()244     public void testPasswords() throws Exception {
245         unlockSystemUser();
246         Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
247         Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
248         mAms.addAccountExplicitly(a11, "p11", null);
249         mAms.addAccountExplicitly(a12, "p12", null);
250 
251         assertEquals("p11", mAms.getPassword(a11));
252         assertEquals("p12", mAms.getPassword(a12));
253 
254         mAms.setPassword(a11, "p11b");
255 
256         assertEquals("p11b", mAms.getPassword(a11));
257         assertEquals("p12", mAms.getPassword(a12));
258     }
259 
260     @SmallTest
testUserdata()261     public void testUserdata() throws Exception {
262         unlockSystemUser();
263         Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
264         Bundle u11 = new Bundle();
265         u11.putString("a", "a_a11");
266         u11.putString("b", "b_a11");
267         u11.putString("c", "c_a11");
268         Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
269         Bundle u12 = new Bundle();
270         u12.putString("a", "a_a12");
271         u12.putString("b", "b_a12");
272         u12.putString("c", "c_a12");
273         mAms.addAccountExplicitly(a11, "p11", u11);
274         mAms.addAccountExplicitly(a12, "p12", u12);
275 
276         assertEquals("a_a11", mAms.getUserData(a11, "a"));
277         assertEquals("b_a11", mAms.getUserData(a11, "b"));
278         assertEquals("c_a11", mAms.getUserData(a11, "c"));
279         assertEquals("a_a12", mAms.getUserData(a12, "a"));
280         assertEquals("b_a12", mAms.getUserData(a12, "b"));
281         assertEquals("c_a12", mAms.getUserData(a12, "c"));
282 
283         mAms.setUserData(a11, "b", "b_a11b");
284         mAms.setUserData(a12, "c", null);
285 
286         assertEquals("a_a11", mAms.getUserData(a11, "a"));
287         assertEquals("b_a11b", mAms.getUserData(a11, "b"));
288         assertEquals("c_a11", mAms.getUserData(a11, "c"));
289         assertEquals("a_a12", mAms.getUserData(a12, "a"));
290         assertEquals("b_a12", mAms.getUserData(a12, "b"));
291         assertNull(mAms.getUserData(a12, "c"));
292     }
293 
294     @SmallTest
testAuthtokens()295     public void testAuthtokens() throws Exception {
296         unlockSystemUser();
297         Account a11 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
298         Account a12 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
299         mAms.addAccountExplicitly(a11, "p11", null);
300         mAms.addAccountExplicitly(a12, "p12", null);
301 
302         mAms.setAuthToken(a11, "att1", "a11_att1");
303         mAms.setAuthToken(a11, "att2", "a11_att2");
304         mAms.setAuthToken(a11, "att3", "a11_att3");
305         mAms.setAuthToken(a12, "att1", "a12_att1");
306         mAms.setAuthToken(a12, "att2", "a12_att2");
307         mAms.setAuthToken(a12, "att3", "a12_att3");
308 
309         assertEquals("a11_att1", mAms.peekAuthToken(a11, "att1"));
310         assertEquals("a11_att2", mAms.peekAuthToken(a11, "att2"));
311         assertEquals("a11_att3", mAms.peekAuthToken(a11, "att3"));
312         assertEquals("a12_att1", mAms.peekAuthToken(a12, "att1"));
313         assertEquals("a12_att2", mAms.peekAuthToken(a12, "att2"));
314         assertEquals("a12_att3", mAms.peekAuthToken(a12, "att3"));
315 
316         mAms.setAuthToken(a11, "att3", "a11_att3b");
317         mAms.invalidateAuthToken(a12.type, "a12_att2");
318 
319         assertEquals("a11_att1", mAms.peekAuthToken(a11, "att1"));
320         assertEquals("a11_att2", mAms.peekAuthToken(a11, "att2"));
321         assertEquals("a11_att3b", mAms.peekAuthToken(a11, "att3"));
322         assertEquals("a12_att1", mAms.peekAuthToken(a12, "att1"));
323         assertNull(mAms.peekAuthToken(a12, "att2"));
324         assertEquals("a12_att3", mAms.peekAuthToken(a12, "att3"));
325 
326         assertNull(mAms.peekAuthToken(a12, "att2"));
327     }
328 
329     @SmallTest
testRemovedAccountSync()330     public void testRemovedAccountSync() throws Exception {
331         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
332         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
333         unlockSystemUser();
334         Account a1 = new Account("account1", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
335         Account a2 = new Account("account2", AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2);
336         mAms.addAccountExplicitly(a1, "p1", null);
337         mAms.addAccountExplicitly(a2, "p2", null);
338 
339         Context originalContext = ((MyMockContext)getContext()).mTestContext;
340         // create a separate instance of AMS. It initially assumes that user0 is locked
341         AccountManagerService ams2 = new AccountManagerService(mTestInjector);
342 
343         // Verify that account can be removed when user is locked
344         ams2.removeAccountInternal(a1);
345         Account[] accounts = ams2.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName());
346         assertEquals(1, accounts.length);
347         assertEquals("Only a2 should be returned", a2, accounts[0]);
348 
349         // Verify that CE db file is unchanged and still has 2 accounts
350         String ceDatabaseName = mTestInjector.getCeDatabaseName(UserHandle.USER_SYSTEM);
351         int accountsNumber = readNumberOfAccountsFromDbFile(originalContext, ceDatabaseName);
352         assertEquals("CE database should still have 2 accounts", 2, accountsNumber);
353 
354         // Unlock the user and verify that db has been updated
355         ams2.onUserUnlocked(newIntentForUser(UserHandle.USER_SYSTEM));
356         accounts = ams2.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName());
357         assertEquals(1, accounts.length);
358         assertEquals("Only a2 should be returned", a2, accounts[0]);
359         accountsNumber = readNumberOfAccountsFromDbFile(originalContext, ceDatabaseName);
360         assertEquals("CE database should now have 1 account", 1, accountsNumber);
361     }
362 
363     @SmallTest
testPreNDatabaseMigration()364     public void testPreNDatabaseMigration() throws Exception {
365         String preNDatabaseName = mTestInjector.getPreNDatabaseName(UserHandle.USER_SYSTEM);
366         Context originalContext = ((MyMockContext) getContext()).mTestContext;
367         PreNTestDatabaseHelper.createV4Database(originalContext, preNDatabaseName);
368         // Assert that database was created with 1 account
369         int n = readNumberOfAccountsFromDbFile(originalContext, preNDatabaseName);
370         assertEquals("pre-N database should have 1 account", 1, n);
371 
372         // Start testing
373         unlockSystemUser();
374         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
375         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
376         Account[] accounts = mAms.getAccounts(null, mContext.getOpPackageName());
377         assertEquals("1 account should be migrated", 1, accounts.length);
378         assertEquals(PreNTestDatabaseHelper.ACCOUNT_NAME, accounts[0].name);
379         assertEquals(PreNTestDatabaseHelper.ACCOUNT_PASSWORD, mAms.getPassword(accounts[0]));
380         assertEquals("Authtoken should be migrated",
381                 PreNTestDatabaseHelper.TOKEN_STRING,
382                 mAms.peekAuthToken(accounts[0], PreNTestDatabaseHelper.TOKEN_TYPE));
383 
384         assertFalse("pre-N database file should be removed but was found at " + preNDatabaseName,
385                 new File(preNDatabaseName).exists());
386 
387         // Verify that ce/de files are present
388         String deDatabaseName = mTestInjector.getDeDatabaseName(UserHandle.USER_SYSTEM);
389         String ceDatabaseName = mTestInjector.getCeDatabaseName(UserHandle.USER_SYSTEM);
390         assertTrue("DE database file should be created at " + deDatabaseName,
391                 new File(deDatabaseName).exists());
392         assertTrue("CE database file should be created at " + ceDatabaseName,
393                 new File(ceDatabaseName).exists());
394     }
395 
396     @SmallTest
testStartAddAccountSessionWithNullResponse()397     public void testStartAddAccountSessionWithNullResponse() throws Exception {
398         unlockSystemUser();
399         try {
400             mAms.startAddAccountSession(
401                 null, // response
402                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
403                 "authTokenType",
404                 null, // requiredFeatures
405                 true, // expectActivityLaunch
406                 null); // optionsIn
407             fail("IllegalArgumentException expected. But no exception was thrown.");
408         } catch (IllegalArgumentException e) {
409             // IllegalArgumentException is expected.
410         }
411     }
412 
413     @SmallTest
testStartAddAccountSessionWithNullAccountType()414     public void testStartAddAccountSessionWithNullAccountType() throws Exception {
415         unlockSystemUser();
416         try {
417             mAms.startAddAccountSession(
418                     mMockAccountManagerResponse, // response
419                     null, // accountType
420                     "authTokenType",
421                     null, // requiredFeatures
422                     true, // expectActivityLaunch
423                     null); // optionsIn
424             fail("IllegalArgumentException expected. But no exception was thrown.");
425         } catch (IllegalArgumentException e) {
426             // IllegalArgumentException is expected.
427         }
428     }
429 
430     @SmallTest
testStartAddAccountSessionUserCannotModifyAccountNoDPM()431     public void testStartAddAccountSessionUserCannotModifyAccountNoDPM() throws Exception {
432         unlockSystemUser();
433         Bundle bundle = new Bundle();
434         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
435         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
436         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
437 
438         mAms.startAddAccountSession(
439                 mMockAccountManagerResponse, // response
440                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
441                 "authTokenType",
442                 null, // requiredFeatures
443                 true, // expectActivityLaunch
444                 null); // optionsIn
445         verify(mMockAccountManagerResponse).onError(
446                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
447         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
448 
449         // verify the intent for default CantAddAccountActivity is sent.
450         Intent intent = mIntentCaptor.getValue();
451         assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName());
452         assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0),
453                 AccountManager.ERROR_CODE_USER_RESTRICTED);
454     }
455 
456     @SmallTest
testStartAddAccountSessionUserCannotModifyAccountWithDPM()457     public void testStartAddAccountSessionUserCannotModifyAccountWithDPM() throws Exception {
458         unlockSystemUser();
459         Bundle bundle = new Bundle();
460         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
461         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
462         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
463         LocalServices.addService(
464                 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal);
465         when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent(
466                 anyInt(), anyString())).thenReturn(new Intent());
467         when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent(
468                 anyInt(), anyBoolean())).thenReturn(new Intent());
469 
470         mAms.startAddAccountSession(
471                 mMockAccountManagerResponse, // response
472                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
473                 "authTokenType",
474                 null, // requiredFeatures
475                 true, // expectActivityLaunch
476                 null); // optionsIn
477 
478         verify(mMockAccountManagerResponse).onError(
479                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
480         verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM));
481         verify(mMockDevicePolicyManagerInternal).createUserRestrictionSupportIntent(
482                 anyInt(), anyString());
483     }
484 
485     @SmallTest
testStartAddAccountSessionUserCannotModifyAccountForTypeNoDPM()486     public void testStartAddAccountSessionUserCannotModifyAccountForTypeNoDPM() throws Exception {
487         unlockSystemUser();
488         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
489                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
490         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
491 
492         mAms.startAddAccountSession(
493                 mMockAccountManagerResponse, // response
494                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
495                 "authTokenType",
496                 null, // requiredFeatures
497                 true, // expectActivityLaunch
498                 null); // optionsIn
499 
500         verify(mMockAccountManagerResponse).onError(
501                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
502         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
503 
504         // verify the intent for default CantAddAccountActivity is sent.
505         Intent intent = mIntentCaptor.getValue();
506         assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName());
507         assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0),
508                 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
509     }
510 
511     @SmallTest
testStartAddAccountSessionUserCannotModifyAccountForTypeWithDPM()512     public void testStartAddAccountSessionUserCannotModifyAccountForTypeWithDPM() throws Exception {
513         unlockSystemUser();
514         when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn(
515                 mMockDevicePolicyManager);
516         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
517                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
518 
519         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
520         LocalServices.addService(
521                 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal);
522         when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent(
523                 anyInt(), anyString())).thenReturn(new Intent());
524         when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent(
525                 anyInt(), anyBoolean())).thenReturn(new Intent());
526 
527         mAms.startAddAccountSession(
528                 mMockAccountManagerResponse, // response
529                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
530                 "authTokenType",
531                 null, // requiredFeatures
532                 true, // expectActivityLaunch
533                 null); // optionsIn
534 
535         verify(mMockAccountManagerResponse).onError(
536                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
537         verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM));
538         verify(mMockDevicePolicyManagerInternal).createShowAdminSupportIntent(
539                 anyInt(), anyBoolean());
540     }
541 
542     @SmallTest
testStartAddAccountSessionSuccessWithoutPasswordForwarding()543     public void testStartAddAccountSessionSuccessWithoutPasswordForwarding() throws Exception {
544         unlockSystemUser();
545         when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn(
546                 PackageManager.PERMISSION_DENIED);
547 
548         final CountDownLatch latch = new CountDownLatch(1);
549         Response response = new Response(latch, mMockAccountManagerResponse);
550         Bundle options = createOptionsWithAccountName(
551                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS);
552         mAms.startAddAccountSession(
553                 response, // response
554                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
555                 "authTokenType",
556                 null, // requiredFeatures
557                 false, // expectActivityLaunch
558                 options); // optionsIn
559         waitForLatch(latch);
560         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
561         Bundle result = mBundleCaptor.getValue();
562         Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
563         assertNotNull(sessionBundle);
564         // Assert that session bundle is encrypted and hence data not visible.
565         assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1));
566         // Assert password is not returned
567         assertNull(result.getString(AccountManager.KEY_PASSWORD));
568         assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null));
569         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN,
570                 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN));
571     }
572 
573     @SmallTest
testStartAddAccountSessionSuccessWithPasswordForwarding()574     public void testStartAddAccountSessionSuccessWithPasswordForwarding() throws Exception {
575         unlockSystemUser();
576         when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn(
577                 PackageManager.PERMISSION_GRANTED);
578 
579         final CountDownLatch latch = new CountDownLatch(1);
580         Response response = new Response(latch, mMockAccountManagerResponse);
581         Bundle options = createOptionsWithAccountName(
582                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS);
583         mAms.startAddAccountSession(
584                 response, // response
585                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
586                 "authTokenType",
587                 null, // requiredFeatures
588                 false, // expectActivityLaunch
589                 options); // optionsIn
590 
591         waitForLatch(latch);
592         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
593         Bundle result = mBundleCaptor.getValue();
594         Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
595         assertNotNull(sessionBundle);
596         // Assert that session bundle is encrypted and hence data not visible.
597         assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1));
598         // Assert password is returned
599         assertEquals(result.getString(AccountManager.KEY_PASSWORD),
600                 AccountManagerServiceTestFixtures.ACCOUNT_PASSWORD);
601         assertNull(result.getString(AccountManager.KEY_AUTHTOKEN));
602         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN,
603                 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN));
604     }
605 
606     @SmallTest
testStartAddAccountSessionReturnWithInvalidIntent()607     public void testStartAddAccountSessionReturnWithInvalidIntent() throws Exception {
608         unlockSystemUser();
609         ResolveInfo resolveInfo = new ResolveInfo();
610         resolveInfo.activityInfo = new ActivityInfo();
611         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
612         when(mMockPackageManager.resolveActivityAsUser(
613                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
614         when(mMockPackageManager.checkSignatures(
615                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
616         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
617                 .thenReturn(false);
618 
619         final CountDownLatch latch = new CountDownLatch(1);
620         Response response = new Response(latch, mMockAccountManagerResponse);
621         Bundle options = createOptionsWithAccountName(
622                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE);
623 
624         mAms.startAddAccountSession(
625                 response, // response
626                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
627                 "authTokenType",
628                 null, // requiredFeatures
629                 true, // expectActivityLaunch
630                 options); // optionsIn
631         waitForLatch(latch);
632         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
633         verify(mMockAccountManagerResponse).onError(
634                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
635     }
636 
637     @SmallTest
testStartAddAccountSessionReturnWithValidIntent()638     public void testStartAddAccountSessionReturnWithValidIntent() throws Exception {
639         unlockSystemUser();
640         ResolveInfo resolveInfo = new ResolveInfo();
641         resolveInfo.activityInfo = new ActivityInfo();
642         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
643         when(mMockPackageManager.resolveActivityAsUser(
644                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
645         when(mMockPackageManager.checkSignatures(
646                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
647 
648         final CountDownLatch latch = new CountDownLatch(1);
649         Response response = new Response(latch, mMockAccountManagerResponse);
650         Bundle options = createOptionsWithAccountName(
651                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE);
652 
653         mAms.startAddAccountSession(
654                 response, // response
655                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
656                 "authTokenType",
657                 null, // requiredFeatures
658                 true, // expectActivityLaunch
659                 options); // optionsIn
660         waitForLatch(latch);
661 
662         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
663         Bundle result = mBundleCaptor.getValue();
664         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
665         assertNotNull(intent);
666         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
667         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
668     }
669 
670     @SmallTest
testStartAddAccountSessionError()671     public void testStartAddAccountSessionError() throws Exception {
672         unlockSystemUser();
673         Bundle options = createOptionsWithAccountName(
674                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR);
675         options.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_INVALID_RESPONSE);
676         options.putString(AccountManager.KEY_ERROR_MESSAGE,
677                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
678 
679         final CountDownLatch latch = new CountDownLatch(1);
680         Response response = new Response(latch, mMockAccountManagerResponse);
681         mAms.startAddAccountSession(
682                 response, // response
683                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
684                 "authTokenType",
685                 null, // requiredFeatures
686                 false, // expectActivityLaunch
687                 options); // optionsIn
688 
689         waitForLatch(latch);
690         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
691                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
692         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
693     }
694 
695     @SmallTest
testStartUpdateCredentialsSessionWithNullResponse()696     public void testStartUpdateCredentialsSessionWithNullResponse() throws Exception {
697         unlockSystemUser();
698         try {
699             mAms.startUpdateCredentialsSession(
700                 null, // response
701                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
702                 "authTokenType",
703                 true, // expectActivityLaunch
704                 null); // optionsIn
705             fail("IllegalArgumentException expected. But no exception was thrown.");
706         } catch (IllegalArgumentException e) {
707             // IllegalArgumentException is expected.
708         }
709     }
710 
711     @SmallTest
testStartUpdateCredentialsSessionWithNullAccount()712     public void testStartUpdateCredentialsSessionWithNullAccount() throws Exception {
713         unlockSystemUser();
714         try {
715             mAms.startUpdateCredentialsSession(
716                 mMockAccountManagerResponse, // response
717                 null,
718                 "authTokenType",
719                 true, // expectActivityLaunch
720                 null); // optionsIn
721             fail("IllegalArgumentException expected. But no exception was thrown.");
722         } catch (IllegalArgumentException e) {
723             // IllegalArgumentException is expected.
724         }
725     }
726 
727     @SmallTest
testStartUpdateCredentialsSessionSuccessWithoutPasswordForwarding()728     public void testStartUpdateCredentialsSessionSuccessWithoutPasswordForwarding()
729             throws Exception {
730         unlockSystemUser();
731         when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn(
732                 PackageManager.PERMISSION_DENIED);
733 
734         final CountDownLatch latch = new CountDownLatch(1);
735         Response response = new Response(latch, mMockAccountManagerResponse);
736         Bundle options = createOptionsWithAccountName(
737             AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS);
738         mAms.startUpdateCredentialsSession(
739                 response, // response
740                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
741                 "authTokenType",
742                 false, // expectActivityLaunch
743                 options); // optionsIn
744         waitForLatch(latch);
745         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
746         Bundle result = mBundleCaptor.getValue();
747         Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
748         assertNotNull(sessionBundle);
749         // Assert that session bundle is encrypted and hence data not visible.
750         assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1));
751         // Assert password is not returned
752         assertNull(result.getString(AccountManager.KEY_PASSWORD));
753         assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null));
754         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN,
755                 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN));
756     }
757 
758     @SmallTest
testStartUpdateCredentialsSessionSuccessWithPasswordForwarding()759     public void testStartUpdateCredentialsSessionSuccessWithPasswordForwarding() throws Exception {
760         unlockSystemUser();
761         when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn(
762                 PackageManager.PERMISSION_GRANTED);
763 
764         final CountDownLatch latch = new CountDownLatch(1);
765         Response response = new Response(latch, mMockAccountManagerResponse);
766         Bundle options = createOptionsWithAccountName(
767             AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS);
768         mAms.startUpdateCredentialsSession(
769                 response, // response
770                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
771                 "authTokenType",
772                 false, // expectActivityLaunch
773                 options); // optionsIn
774 
775         waitForLatch(latch);
776         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
777         Bundle result = mBundleCaptor.getValue();
778         Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
779         assertNotNull(sessionBundle);
780         // Assert that session bundle is encrypted and hence data not visible.
781         assertNull(sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1));
782         // Assert password is returned
783         assertEquals(result.getString(AccountManager.KEY_PASSWORD),
784                 AccountManagerServiceTestFixtures.ACCOUNT_PASSWORD);
785         assertNull(result.getString(AccountManager.KEY_AUTHTOKEN));
786         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN,
787                 result.getString(AccountManager.KEY_ACCOUNT_STATUS_TOKEN));
788     }
789 
790     @SmallTest
testStartUpdateCredentialsSessionReturnWithInvalidIntent()791     public void testStartUpdateCredentialsSessionReturnWithInvalidIntent() throws Exception {
792         unlockSystemUser();
793         ResolveInfo resolveInfo = new ResolveInfo();
794         resolveInfo.activityInfo = new ActivityInfo();
795         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
796         when(mMockPackageManager.resolveActivityAsUser(
797                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
798         when(mMockPackageManager.checkSignatures(
799                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
800         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
801                 .thenReturn(false);
802 
803         final CountDownLatch latch = new CountDownLatch(1);
804         Response response = new Response(latch, mMockAccountManagerResponse);
805         Bundle options = createOptionsWithAccountName(
806                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE);
807 
808         mAms.startUpdateCredentialsSession(
809                 response, // response
810                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
811                 "authTokenType",
812                 true,  // expectActivityLaunch
813                 options); // optionsIn
814 
815         waitForLatch(latch);
816         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
817         verify(mMockAccountManagerResponse).onError(
818                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
819     }
820 
821     @SmallTest
testStartUpdateCredentialsSessionReturnWithValidIntent()822     public void testStartUpdateCredentialsSessionReturnWithValidIntent() throws Exception {
823         unlockSystemUser();
824         ResolveInfo resolveInfo = new ResolveInfo();
825         resolveInfo.activityInfo = new ActivityInfo();
826         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
827         when(mMockPackageManager.resolveActivityAsUser(
828                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
829         when(mMockPackageManager.checkSignatures(
830                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
831 
832         final CountDownLatch latch = new CountDownLatch(1);
833         Response response = new Response(latch, mMockAccountManagerResponse);
834         Bundle options = createOptionsWithAccountName(
835                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE);
836 
837         mAms.startUpdateCredentialsSession(
838                 response, // response
839                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
840                 "authTokenType",
841                 true,  // expectActivityLaunch
842                 options); // optionsIn
843 
844         waitForLatch(latch);
845 
846         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
847         Bundle result = mBundleCaptor.getValue();
848         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
849         assertNotNull(intent);
850         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
851         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
852     }
853 
854     @SmallTest
testStartUpdateCredentialsSessionError()855     public void testStartUpdateCredentialsSessionError() throws Exception {
856         unlockSystemUser();
857         Bundle options = createOptionsWithAccountName(
858                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR);
859         options.putInt(AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_INVALID_RESPONSE);
860         options.putString(AccountManager.KEY_ERROR_MESSAGE,
861                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
862 
863         final CountDownLatch latch = new CountDownLatch(1);
864         Response response = new Response(latch, mMockAccountManagerResponse);
865 
866         mAms.startUpdateCredentialsSession(
867                 response, // response
868                 AccountManagerServiceTestFixtures.ACCOUNT_ERROR,
869                 "authTokenType",
870                 true,  // expectActivityLaunch
871                 options); // optionsIn
872 
873         waitForLatch(latch);
874         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
875                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
876         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
877     }
878 
879     @SmallTest
testFinishSessionAsUserWithNullResponse()880     public void testFinishSessionAsUserWithNullResponse() throws Exception {
881         unlockSystemUser();
882         try {
883             mAms.finishSessionAsUser(
884                 null, // response
885                 createEncryptedSessionBundle(
886                         AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
887                 false, // expectActivityLaunch
888                 createAppBundle(), // appInfo
889                 UserHandle.USER_SYSTEM);
890             fail("IllegalArgumentException expected. But no exception was thrown.");
891         } catch (IllegalArgumentException e) {
892             // IllegalArgumentException is expected.
893         }
894     }
895 
896     @SmallTest
testFinishSessionAsUserWithNullSessionBundle()897     public void testFinishSessionAsUserWithNullSessionBundle() throws Exception {
898         unlockSystemUser();
899         try {
900             mAms.finishSessionAsUser(
901                 mMockAccountManagerResponse, // response
902                 null, // sessionBundle
903                 false, // expectActivityLaunch
904                 createAppBundle(), // appInfo
905                 UserHandle.USER_SYSTEM);
906             fail("IllegalArgumentException expected. But no exception was thrown.");
907         } catch (IllegalArgumentException e) {
908             // IllegalArgumentException is expected.
909         }
910     }
911 
912     @SmallTest
testFinishSessionAsUserUserCannotModifyAccountNoDPM()913     public void testFinishSessionAsUserUserCannotModifyAccountNoDPM() throws Exception {
914         unlockSystemUser();
915         Bundle bundle = new Bundle();
916         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
917         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
918         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
919 
920         mAms.finishSessionAsUser(
921             mMockAccountManagerResponse, // response
922             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
923             false, // expectActivityLaunch
924             createAppBundle(), // appInfo
925             2); // fake user id
926 
927         verify(mMockAccountManagerResponse).onError(
928                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
929         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.of(2)));
930 
931         // verify the intent for default CantAddAccountActivity is sent.
932         Intent intent = mIntentCaptor.getValue();
933         assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName());
934         assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0),
935                 AccountManager.ERROR_CODE_USER_RESTRICTED);
936     }
937 
938     @SmallTest
testFinishSessionAsUserUserCannotModifyAccountWithDPM()939     public void testFinishSessionAsUserUserCannotModifyAccountWithDPM() throws Exception {
940         unlockSystemUser();
941         Bundle bundle = new Bundle();
942         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
943         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
944         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
945         LocalServices.addService(
946                 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal);
947         when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent(
948                 anyInt(), anyString())).thenReturn(new Intent());
949         when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent(
950                 anyInt(), anyBoolean())).thenReturn(new Intent());
951 
952         mAms.finishSessionAsUser(
953             mMockAccountManagerResponse, // response
954             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
955             false, // expectActivityLaunch
956             createAppBundle(), // appInfo
957             2); // fake user id
958 
959         verify(mMockAccountManagerResponse).onError(
960                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
961         verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.of(2)));
962         verify(mMockDevicePolicyManagerInternal).createUserRestrictionSupportIntent(
963                 anyInt(), anyString());
964     }
965 
966     @SmallTest
testFinishSessionAsUserWithBadSessionBundle()967     public void testFinishSessionAsUserWithBadSessionBundle() throws Exception {
968         unlockSystemUser();
969 
970         Bundle badSessionBundle = new Bundle();
971         badSessionBundle.putString("any", "any");
972         mAms.finishSessionAsUser(
973             mMockAccountManagerResponse, // response
974             badSessionBundle, // sessionBundle
975             false, // expectActivityLaunch
976             createAppBundle(), // appInfo
977             2); // fake user id
978 
979         verify(mMockAccountManagerResponse).onError(
980                 eq(AccountManager.ERROR_CODE_BAD_REQUEST), anyString());
981     }
982 
983     @SmallTest
testFinishSessionAsUserWithBadAccountType()984     public void testFinishSessionAsUserWithBadAccountType() throws Exception {
985         unlockSystemUser();
986 
987         mAms.finishSessionAsUser(
988             mMockAccountManagerResponse, // response
989             createEncryptedSessionBundleWithNoAccountType(
990                     AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
991             false, // expectActivityLaunch
992             createAppBundle(), // appInfo
993             2); // fake user id
994 
995         verify(mMockAccountManagerResponse).onError(
996                 eq(AccountManager.ERROR_CODE_BAD_ARGUMENTS), anyString());
997     }
998 
999     @SmallTest
testFinishSessionAsUserUserCannotModifyAccountForTypeNoDPM()1000     public void testFinishSessionAsUserUserCannotModifyAccountForTypeNoDPM() throws Exception {
1001         unlockSystemUser();
1002         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
1003                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
1004         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
1005 
1006         mAms.finishSessionAsUser(
1007             mMockAccountManagerResponse, // response
1008             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
1009             false, // expectActivityLaunch
1010             createAppBundle(), // appInfo
1011             2); // fake user id
1012 
1013         verify(mMockAccountManagerResponse).onError(
1014                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
1015         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.of(2)));
1016 
1017         // verify the intent for default CantAddAccountActivity is sent.
1018         Intent intent = mIntentCaptor.getValue();
1019         assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName());
1020         assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0),
1021                 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1022     }
1023 
1024     @SmallTest
testFinishSessionAsUserUserCannotModifyAccountForTypeWithDPM()1025     public void testFinishSessionAsUserUserCannotModifyAccountForTypeWithDPM() throws Exception {
1026         unlockSystemUser();
1027         when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn(
1028                 mMockDevicePolicyManager);
1029         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
1030                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
1031 
1032         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
1033         LocalServices.addService(
1034                 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal);
1035         when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent(
1036                 anyInt(), anyString())).thenReturn(new Intent());
1037         when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent(
1038                 anyInt(), anyBoolean())).thenReturn(new Intent());
1039 
1040         mAms.finishSessionAsUser(
1041             mMockAccountManagerResponse, // response
1042             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
1043             false, // expectActivityLaunch
1044             createAppBundle(), // appInfo
1045             2); // fake user id
1046 
1047         verify(mMockAccountManagerResponse).onError(
1048                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
1049         verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.of(2)));
1050         verify(mMockDevicePolicyManagerInternal).createShowAdminSupportIntent(
1051                 anyInt(), anyBoolean());
1052     }
1053 
1054     @SmallTest
testFinishSessionAsUserSuccess()1055     public void testFinishSessionAsUserSuccess() throws Exception {
1056         unlockSystemUser();
1057         final CountDownLatch latch = new CountDownLatch(1);
1058         Response response = new Response(latch, mMockAccountManagerResponse);
1059         mAms.finishSessionAsUser(
1060             response, // response
1061             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
1062             false, // expectActivityLaunch
1063             createAppBundle(), // appInfo
1064             UserHandle.USER_SYSTEM);
1065 
1066         waitForLatch(latch);
1067         // Verify notification is cancelled
1068         verify(mMockNotificationManager).cancelNotificationWithTag(
1069                 anyString(), nullable(String.class), anyInt(), anyInt());
1070 
1071         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1072         Bundle result = mBundleCaptor.getValue();
1073         Bundle sessionBundle = result.getBundle(AccountManager.KEY_ACCOUNT_SESSION_BUNDLE);
1074         assertNotNull(sessionBundle);
1075         // Assert that session bundle is decrypted and hence data is visible.
1076         assertEquals(AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1,
1077                 sessionBundle.getString(AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1));
1078         // Assert finishSessionAsUser added calling uid and pid into the sessionBundle
1079         assertTrue(sessionBundle.containsKey(AccountManager.KEY_CALLER_UID));
1080         assertTrue(sessionBundle.containsKey(AccountManager.KEY_CALLER_PID));
1081         assertEquals(sessionBundle.getString(
1082                 AccountManager.KEY_ANDROID_PACKAGE_NAME), "APCT.package");
1083 
1084         // Verify response data
1085         assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null));
1086         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME,
1087                 result.getString(AccountManager.KEY_ACCOUNT_NAME));
1088         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
1089                 result.getString(AccountManager.KEY_ACCOUNT_TYPE));
1090     }
1091 
1092     @SmallTest
testFinishSessionAsUserReturnWithInvalidIntent()1093     public void testFinishSessionAsUserReturnWithInvalidIntent() throws Exception {
1094         unlockSystemUser();
1095         ResolveInfo resolveInfo = new ResolveInfo();
1096         resolveInfo.activityInfo = new ActivityInfo();
1097         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
1098         when(mMockPackageManager.resolveActivityAsUser(
1099                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
1100         when(mMockPackageManager.checkSignatures(
1101                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
1102         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
1103                 .thenReturn(false);
1104 
1105         final CountDownLatch latch = new CountDownLatch(1);
1106         Response response = new Response(latch, mMockAccountManagerResponse);
1107 
1108         mAms.finishSessionAsUser(
1109             response, // response
1110             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE),
1111             true, // expectActivityLaunch
1112             createAppBundle(), // appInfo
1113             UserHandle.USER_SYSTEM);
1114 
1115         waitForLatch(latch);
1116         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1117         verify(mMockAccountManagerResponse).onError(
1118                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
1119     }
1120 
1121     @SmallTest
testFinishSessionAsUserReturnWithValidIntent()1122     public void testFinishSessionAsUserReturnWithValidIntent() throws Exception {
1123         unlockSystemUser();
1124         ResolveInfo resolveInfo = new ResolveInfo();
1125         resolveInfo.activityInfo = new ActivityInfo();
1126         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
1127         when(mMockPackageManager.resolveActivityAsUser(
1128                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
1129         when(mMockPackageManager.checkSignatures(
1130                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
1131 
1132         final CountDownLatch latch = new CountDownLatch(1);
1133         Response response = new Response(latch, mMockAccountManagerResponse);
1134 
1135         mAms.finishSessionAsUser(
1136             response, // response
1137             createEncryptedSessionBundle(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE),
1138             true, // expectActivityLaunch
1139             createAppBundle(), // appInfo
1140             UserHandle.USER_SYSTEM);
1141 
1142         waitForLatch(latch);
1143 
1144         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1145         Bundle result = mBundleCaptor.getValue();
1146         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
1147         assertNotNull(intent);
1148         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
1149         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
1150     }
1151 
1152     @SmallTest
testFinishSessionAsUserError()1153     public void testFinishSessionAsUserError() throws Exception {
1154         unlockSystemUser();
1155         Bundle sessionBundle = createEncryptedSessionBundleWithError(
1156                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR);
1157 
1158         final CountDownLatch latch = new CountDownLatch(1);
1159         Response response = new Response(latch, mMockAccountManagerResponse);
1160 
1161         mAms.finishSessionAsUser(
1162             response, // response
1163             sessionBundle,
1164             false, // expectActivityLaunch
1165             createAppBundle(), // appInfo
1166             UserHandle.USER_SYSTEM);
1167 
1168         waitForLatch(latch);
1169         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
1170                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
1171         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1172     }
1173 
1174     @SmallTest
testIsCredentialsUpdatedSuggestedWithNullResponse()1175     public void testIsCredentialsUpdatedSuggestedWithNullResponse() throws Exception {
1176         unlockSystemUser();
1177         try {
1178             mAms.isCredentialsUpdateSuggested(
1179                 null, // response
1180                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1181                 AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN);
1182             fail("IllegalArgumentException expected. But no exception was thrown.");
1183         } catch (IllegalArgumentException e) {
1184             // IllegalArgumentException is expected.
1185         }
1186     }
1187 
1188     @SmallTest
testIsCredentialsUpdatedSuggestedWithNullAccount()1189     public void testIsCredentialsUpdatedSuggestedWithNullAccount() throws Exception {
1190         unlockSystemUser();
1191         try {
1192             mAms.isCredentialsUpdateSuggested(
1193                 mMockAccountManagerResponse,
1194                 null, // account
1195                 AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN);
1196             fail("IllegalArgumentException expected. But no exception was thrown.");
1197         } catch (IllegalArgumentException e) {
1198             // IllegalArgumentException is expected.
1199         }
1200     }
1201 
1202     @SmallTest
testIsCredentialsUpdatedSuggestedWithEmptyStatusToken()1203     public void testIsCredentialsUpdatedSuggestedWithEmptyStatusToken() throws Exception {
1204         unlockSystemUser();
1205         try {
1206             mAms.isCredentialsUpdateSuggested(
1207                 mMockAccountManagerResponse,
1208                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1209                 null);
1210             fail("IllegalArgumentException expected. But no exception was thrown.");
1211         } catch (IllegalArgumentException e) {
1212             // IllegalArgumentException is expected.
1213         }
1214     }
1215 
1216     @SmallTest
testIsCredentialsUpdatedSuggestedError()1217     public void testIsCredentialsUpdatedSuggestedError() throws Exception {
1218         unlockSystemUser();
1219         final CountDownLatch latch = new CountDownLatch(1);
1220         Response response = new Response(latch, mMockAccountManagerResponse);
1221 
1222         mAms.isCredentialsUpdateSuggested(
1223             response,
1224             AccountManagerServiceTestFixtures.ACCOUNT_ERROR,
1225             AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN);
1226 
1227         waitForLatch(latch);
1228         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
1229                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
1230         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1231     }
1232 
1233     @SmallTest
testIsCredentialsUpdatedSuggestedSuccess()1234     public void testIsCredentialsUpdatedSuggestedSuccess() throws Exception {
1235         unlockSystemUser();
1236         final CountDownLatch latch = new CountDownLatch(1);
1237         Response response = new Response(latch, mMockAccountManagerResponse);
1238 
1239         mAms.isCredentialsUpdateSuggested(
1240             response,
1241             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1242             AccountManagerServiceTestFixtures.ACCOUNT_STATUS_TOKEN);
1243 
1244         waitForLatch(latch);
1245         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1246         Bundle result = mBundleCaptor.getValue();
1247         boolean needUpdate = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
1248         assertTrue(needUpdate);
1249     }
1250 
1251     @SmallTest
testHasFeaturesWithNullResponse()1252     public void testHasFeaturesWithNullResponse() throws Exception {
1253         unlockSystemUser();
1254         try {
1255             mAms.hasFeatures(
1256                 null, // response
1257                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1258                 new String[] {"feature1", "feature2"}, // features
1259                 "testPackage"); // opPackageName
1260             fail("IllegalArgumentException expected. But no exception was thrown.");
1261         } catch (IllegalArgumentException e) {
1262             // IllegalArgumentException is expected.
1263         }
1264     }
1265 
1266     @SmallTest
testHasFeaturesWithNullAccount()1267     public void testHasFeaturesWithNullAccount() throws Exception {
1268         unlockSystemUser();
1269         try {
1270             mAms.hasFeatures(
1271                 mMockAccountManagerResponse, // response
1272                 null, // account
1273                 new String[] {"feature1", "feature2"}, // features
1274                 "testPackage"); // opPackageName
1275             fail("IllegalArgumentException expected. But no exception was thrown.");
1276         } catch (IllegalArgumentException e) {
1277             // IllegalArgumentException is expected.
1278         }
1279     }
1280 
1281     @SmallTest
testHasFeaturesWithNullFeature()1282     public void testHasFeaturesWithNullFeature() throws Exception {
1283         unlockSystemUser();
1284         try {
1285             mAms.hasFeatures(
1286                     mMockAccountManagerResponse, // response
1287                     AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, // account
1288                     null, // features
1289                     "testPackage"); // opPackageName
1290             fail("IllegalArgumentException expected. But no exception was thrown.");
1291         } catch (IllegalArgumentException e) {
1292             // IllegalArgumentException is expected.
1293         }
1294     }
1295 
1296     @SmallTest
testHasFeaturesReturnNullResult()1297     public void testHasFeaturesReturnNullResult() throws Exception {
1298         unlockSystemUser();
1299         final CountDownLatch latch = new CountDownLatch(1);
1300         Response response = new Response(latch, mMockAccountManagerResponse);
1301         mAms.hasFeatures(
1302                 response, // response
1303                 AccountManagerServiceTestFixtures.ACCOUNT_ERROR, // account
1304                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, // features
1305                 "testPackage"); // opPackageName
1306         waitForLatch(latch);
1307         verify(mMockAccountManagerResponse).onError(
1308                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
1309         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1310     }
1311 
1312     @SmallTest
testHasFeaturesSuccess()1313     public void testHasFeaturesSuccess() throws Exception {
1314         unlockSystemUser();
1315         final CountDownLatch latch = new CountDownLatch(1);
1316         Response response = new Response(latch, mMockAccountManagerResponse);
1317         mAms.hasFeatures(
1318                 response, // response
1319                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, // account
1320                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES, // features
1321                 "testPackage"); // opPackageName
1322         waitForLatch(latch);
1323         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1324         Bundle result = mBundleCaptor.getValue();
1325         boolean hasFeatures = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
1326         assertTrue(hasFeatures);
1327     }
1328 
1329     @SmallTest
testRemoveAccountAsUserWithNullResponse()1330     public void testRemoveAccountAsUserWithNullResponse() throws Exception {
1331         unlockSystemUser();
1332         try {
1333             mAms.removeAccountAsUser(
1334                 null, // response
1335                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1336                 true, // expectActivityLaunch
1337                 UserHandle.USER_SYSTEM);
1338             fail("IllegalArgumentException expected. But no exception was thrown.");
1339         } catch (IllegalArgumentException e) {
1340             // IllegalArgumentException is expected.
1341         }
1342     }
1343 
1344     @SmallTest
testRemoveAccountAsUserWithNullAccount()1345     public void testRemoveAccountAsUserWithNullAccount() throws Exception {
1346         unlockSystemUser();
1347         try {
1348             mAms.removeAccountAsUser(
1349                 mMockAccountManagerResponse, // response
1350                 null, // account
1351                 true, // expectActivityLaunch
1352                 UserHandle.USER_SYSTEM);
1353             fail("IllegalArgumentException expected. But no exception was thrown.");
1354         } catch (IllegalArgumentException e) {
1355             // IllegalArgumentException is expected.
1356         }
1357     }
1358 
1359     @SmallTest
testRemoveAccountAsUserAccountNotManagedByCaller()1360     public void testRemoveAccountAsUserAccountNotManagedByCaller() throws Exception {
1361         unlockSystemUser();
1362         when(mMockPackageManager.checkSignatures(anyInt(), anyInt()))
1363                     .thenReturn(PackageManager.SIGNATURE_NO_MATCH);
1364         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
1365                 .thenReturn(false);
1366         try {
1367             mAms.removeAccountAsUser(
1368                 mMockAccountManagerResponse, // response
1369                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1370                 true, // expectActivityLaunch
1371                 UserHandle.USER_SYSTEM);
1372             fail("SecurityException expected. But no exception was thrown.");
1373         } catch (SecurityException e) {
1374             // SecurityException is expected.
1375         }
1376     }
1377 
1378     @SmallTest
testRemoveAccountAsUserUserCannotModifyAccount()1379     public void testRemoveAccountAsUserUserCannotModifyAccount() throws Exception {
1380         unlockSystemUser();
1381         Bundle bundle = new Bundle();
1382         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
1383         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
1384 
1385         final CountDownLatch latch = new CountDownLatch(1);
1386         Response response = new Response(latch, mMockAccountManagerResponse);
1387 
1388         mAms.removeAccountAsUser(
1389                 response, // response
1390                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1391                 true, // expectActivityLaunch
1392                 UserHandle.USER_SYSTEM);
1393         waitForLatch(latch);
1394         verify(mMockAccountManagerResponse).onError(
1395                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
1396         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1397     }
1398 
1399     @SmallTest
testRemoveAccountAsUserUserCannotModifyAccountType()1400     public void testRemoveAccountAsUserUserCannotModifyAccountType() throws Exception {
1401         unlockSystemUser();
1402         when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn(
1403                 mMockDevicePolicyManager);
1404         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
1405                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
1406 
1407         final CountDownLatch latch = new CountDownLatch(1);
1408         Response response = new Response(latch, mMockAccountManagerResponse);
1409 
1410         mAms.removeAccountAsUser(
1411                 response, // response
1412                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1413                 true, // expectActivityLaunch
1414                 UserHandle.USER_SYSTEM);
1415         waitForLatch(latch);
1416         verify(mMockAccountManagerResponse).onError(
1417                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
1418         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1419     }
1420 
1421     @SmallTest
testRemoveAccountAsUserRemovalAllowed()1422     public void testRemoveAccountAsUserRemovalAllowed() throws Exception {
1423         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
1424         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1425 
1426         unlockSystemUser();
1427         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p1", null);
1428         Account[] addedAccounts =
1429                 mAms.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName());
1430         assertEquals(1, addedAccounts.length);
1431 
1432         final CountDownLatch latch = new CountDownLatch(1);
1433         Response response = new Response(latch, mMockAccountManagerResponse);
1434 
1435         mAms.removeAccountAsUser(
1436                 response, // response
1437                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1438                 true, // expectActivityLaunch
1439                 UserHandle.USER_SYSTEM);
1440         waitForLatch(latch);
1441 
1442         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1443         Bundle result = mBundleCaptor.getValue();
1444         boolean allowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
1445         assertTrue(allowed);
1446         Account[] accounts = mAms.getAccounts(UserHandle.USER_SYSTEM, mContext.getOpPackageName());
1447         assertEquals(0, accounts.length);
1448     }
1449 
1450     @SmallTest
testRemoveAccountAsUserRemovalNotAllowed()1451     public void testRemoveAccountAsUserRemovalNotAllowed() throws Exception {
1452         unlockSystemUser();
1453 
1454         final CountDownLatch latch = new CountDownLatch(1);
1455         Response response = new Response(latch, mMockAccountManagerResponse);
1456 
1457         mAms.removeAccountAsUser(
1458                 response, // response
1459                 AccountManagerServiceTestFixtures.ACCOUNT_ERROR,
1460                 true, // expectActivityLaunch
1461                 UserHandle.USER_SYSTEM);
1462         waitForLatch(latch);
1463 
1464         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1465         Bundle result = mBundleCaptor.getValue();
1466         boolean allowed = result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT);
1467         assertFalse(allowed);
1468     }
1469 
1470     @SmallTest
testRemoveAccountAsUserReturnWithValidIntent()1471     public void testRemoveAccountAsUserReturnWithValidIntent() throws Exception {
1472         unlockSystemUser();
1473         ResolveInfo resolveInfo = new ResolveInfo();
1474         resolveInfo.activityInfo = new ActivityInfo();
1475         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
1476         when(mMockPackageManager.resolveActivityAsUser(
1477                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
1478         when(mMockPackageManager.checkSignatures(
1479                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
1480 
1481         final CountDownLatch latch = new CountDownLatch(1);
1482         Response response = new Response(latch, mMockAccountManagerResponse);
1483 
1484         mAms.removeAccountAsUser(
1485                 response, // response
1486                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
1487                 true, // expectActivityLaunch
1488                 UserHandle.USER_SYSTEM);
1489         waitForLatch(latch);
1490 
1491         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1492         Bundle result = mBundleCaptor.getValue();
1493         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
1494         assertNotNull(intent);
1495     }
1496 
1497     @SmallTest
testGetAccountsByTypeForPackageWhenTypeIsNull()1498     public void testGetAccountsByTypeForPackageWhenTypeIsNull() throws Exception {
1499         unlockSystemUser();
1500         HashMap<String, Integer> visibility1 = new HashMap<>();
1501         visibility1.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE,
1502             AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
1503 
1504         HashMap<String, Integer> visibility2 = new HashMap<>();
1505         visibility2.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE,
1506             AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE);
1507 
1508         mAms.addAccountExplicitlyWithVisibility(
1509             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "P11", null, visibility1);
1510         mAms.addAccountExplicitlyWithVisibility(
1511             AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "P12", null, visibility2);
1512 
1513         Account[] accounts = mAms.getAccountsByTypeForPackage(
1514             null, "otherPackageName",
1515             AccountManagerServiceTestFixtures.CALLER_PACKAGE);
1516         // Only get the USER_MANAGED_NOT_VISIBLE account.
1517         assertEquals(1, accounts.length);
1518         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, accounts[0].name);
1519         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, accounts[0].type);
1520     }
1521 
1522     @SmallTest
testGetAuthTokenLabelWithNullAccountType()1523     public void testGetAuthTokenLabelWithNullAccountType() throws Exception {
1524         unlockSystemUser();
1525         try {
1526             mAms.getAuthTokenLabel(
1527                 mMockAccountManagerResponse, // response
1528                 null, // accountType
1529                 "authTokenType");
1530             fail("IllegalArgumentException expected. But no exception was thrown.");
1531         } catch (IllegalArgumentException e) {
1532             // IllegalArgumentException is expected.
1533         }
1534     }
1535 
1536     @SmallTest
testGetAuthTokenLabelWithNullAuthTokenType()1537     public void testGetAuthTokenLabelWithNullAuthTokenType() throws Exception {
1538         unlockSystemUser();
1539         try {
1540             mAms.getAuthTokenLabel(
1541                 mMockAccountManagerResponse, // response
1542                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1543                 null); // authTokenType
1544             fail("IllegalArgumentException expected. But no exception was thrown.");
1545         } catch (IllegalArgumentException e) {
1546             // IllegalArgumentException is expected.
1547         }
1548     }
1549 
1550     @SmallTest
testGetAuthTokenWithNullResponse()1551     public void testGetAuthTokenWithNullResponse() throws Exception {
1552         unlockSystemUser();
1553         try {
1554             mAms.getAuthToken(
1555                     null, // response
1556                     AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1557                     "authTokenType", // authTokenType
1558                     true, // notifyOnAuthFailure
1559                     true, // expectActivityLaunch
1560                     createGetAuthTokenOptions());
1561             fail("IllegalArgumentException expected. But no exception was thrown.");
1562         } catch (IllegalArgumentException e) {
1563             // IllegalArgumentException is expected.
1564         }
1565     }
1566 
1567     @SmallTest
testGetAuthTokenWithNullAccount()1568     public void testGetAuthTokenWithNullAccount() throws Exception {
1569         unlockSystemUser();
1570         final CountDownLatch latch = new CountDownLatch(1);
1571         Response response = new Response(latch, mMockAccountManagerResponse);
1572         mAms.getAuthToken(
1573                     response, // response
1574                     null, // account
1575                     "authTokenType", // authTokenType
1576                     true, // notifyOnAuthFailure
1577                     true, // expectActivityLaunch
1578                     createGetAuthTokenOptions());
1579         waitForLatch(latch);
1580 
1581         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1582         verify(mMockAccountManagerResponse).onError(
1583                 eq(AccountManager.ERROR_CODE_BAD_ARGUMENTS), anyString());
1584     }
1585 
1586     @SmallTest
testGetAuthTokenWithNullAuthTokenType()1587     public void testGetAuthTokenWithNullAuthTokenType() throws Exception {
1588         unlockSystemUser();
1589         final CountDownLatch latch = new CountDownLatch(1);
1590         Response response = new Response(latch, mMockAccountManagerResponse);
1591         mAms.getAuthToken(
1592                     response, // response
1593                     AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1594                     null, // authTokenType
1595                     true, // notifyOnAuthFailure
1596                     true, // expectActivityLaunch
1597                     createGetAuthTokenOptions());
1598         waitForLatch(latch);
1599 
1600         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1601         verify(mMockAccountManagerResponse).onError(
1602                 eq(AccountManager.ERROR_CODE_BAD_ARGUMENTS), anyString());
1603     }
1604 
1605     @SmallTest
testGetAuthTokenWithInvalidPackage()1606     public void testGetAuthTokenWithInvalidPackage() throws Exception {
1607         unlockSystemUser();
1608         String[] list = new String[]{"test"};
1609         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1610         try {
1611             mAms.getAuthToken(
1612                     mMockAccountManagerResponse, // response
1613                     AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1614                     "authTokenType", // authTokenType
1615                     true, // notifyOnAuthFailure
1616                     true, // expectActivityLaunch
1617                     createGetAuthTokenOptions());
1618             fail("SecurityException expected. But no exception was thrown.");
1619         } catch (SecurityException e) {
1620             // SecurityException is expected.
1621         }
1622     }
1623 
1624     @SmallTest
testGetAuthTokenFromInternal()1625     public void testGetAuthTokenFromInternal() throws Exception {
1626         unlockSystemUser();
1627         when(mMockContext.createPackageContextAsUser(
1628                  anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext);
1629         when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
1630         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
1631         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1632         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
1633 
1634         mAms.setAuthToken(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1635                 "authTokenType", AccountManagerServiceTestFixtures.AUTH_TOKEN);
1636         final CountDownLatch latch = new CountDownLatch(1);
1637         Response response = new Response(latch, mMockAccountManagerResponse);
1638         mAms.getAuthToken(
1639                     response, // response
1640                     AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1641                     "authTokenType", // authTokenType
1642                     true, // notifyOnAuthFailure
1643                     true, // expectActivityLaunch
1644                     createGetAuthTokenOptions());
1645         waitForLatch(latch);
1646 
1647         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1648         Bundle result = mBundleCaptor.getValue();
1649         assertEquals(result.getString(AccountManager.KEY_AUTHTOKEN),
1650                 AccountManagerServiceTestFixtures.AUTH_TOKEN);
1651         assertEquals(result.getString(AccountManager.KEY_ACCOUNT_NAME),
1652                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS);
1653         assertEquals(result.getString(AccountManager.KEY_ACCOUNT_TYPE),
1654                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
1655     }
1656 
1657     @SmallTest
testGetAuthTokenSuccess()1658     public void testGetAuthTokenSuccess() throws Exception {
1659         unlockSystemUser();
1660         when(mMockContext.createPackageContextAsUser(
1661                  anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext);
1662         when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
1663         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
1664         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1665 
1666         final CountDownLatch latch = new CountDownLatch(1);
1667         Response response = new Response(latch, mMockAccountManagerResponse);
1668         mAms.getAuthToken(
1669                     response, // response
1670                     AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
1671                     "authTokenType", // authTokenType
1672                     true, // notifyOnAuthFailure
1673                     false, // expectActivityLaunch
1674                     createGetAuthTokenOptions());
1675         waitForLatch(latch);
1676 
1677         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1678         Bundle result = mBundleCaptor.getValue();
1679         assertEquals(result.getString(AccountManager.KEY_AUTHTOKEN),
1680                 AccountManagerServiceTestFixtures.AUTH_TOKEN);
1681         assertEquals(result.getString(AccountManager.KEY_ACCOUNT_NAME),
1682                 AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS);
1683         assertEquals(result.getString(AccountManager.KEY_ACCOUNT_TYPE),
1684                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
1685     }
1686 
1687     @SmallTest
testGetAuthTokenReturnWithInvalidIntent()1688     public void testGetAuthTokenReturnWithInvalidIntent() throws Exception {
1689         unlockSystemUser();
1690         when(mMockContext.createPackageContextAsUser(
1691                  anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext);
1692         when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
1693         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
1694         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1695         ResolveInfo resolveInfo = new ResolveInfo();
1696         resolveInfo.activityInfo = new ActivityInfo();
1697         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
1698         when(mMockPackageManager.resolveActivityAsUser(
1699                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
1700         when(mMockPackageManager.checkSignatures(
1701                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
1702         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
1703                 .thenReturn(false);
1704 
1705         final CountDownLatch latch = new CountDownLatch(1);
1706         Response response = new Response(latch, mMockAccountManagerResponse);
1707         mAms.getAuthToken(
1708                     response, // response
1709                     AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
1710                     "authTokenType", // authTokenType
1711                     true, // notifyOnAuthFailure
1712                     false, // expectActivityLaunch
1713                     createGetAuthTokenOptions());
1714         waitForLatch(latch);
1715         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1716         verify(mMockAccountManagerResponse).onError(
1717                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
1718     }
1719 
1720     @SmallTest
testGetAuthTokenReturnWithValidIntent()1721     public void testGetAuthTokenReturnWithValidIntent() throws Exception {
1722         unlockSystemUser();
1723         when(mMockContext.createPackageContextAsUser(
1724                  anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext);
1725         when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
1726         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
1727         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1728 
1729         ResolveInfo resolveInfo = new ResolveInfo();
1730         resolveInfo.activityInfo = new ActivityInfo();
1731         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
1732         when(mMockPackageManager.resolveActivityAsUser(
1733                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
1734         when(mMockPackageManager.checkSignatures(
1735                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
1736 
1737         final CountDownLatch latch = new CountDownLatch(1);
1738         Response response = new Response(latch, mMockAccountManagerResponse);
1739         mAms.getAuthToken(
1740                     response, // response
1741                     AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
1742                     "authTokenType", // authTokenType
1743                     false, // notifyOnAuthFailure
1744                     true, // expectActivityLaunch
1745                     createGetAuthTokenOptions());
1746         waitForLatch(latch);
1747         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1748         Bundle result = mBundleCaptor.getValue();
1749         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
1750         assertNotNull(intent);
1751         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
1752         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
1753     }
1754 
1755     @SmallTest
testGetAuthTokenError()1756     public void testGetAuthTokenError() throws Exception {
1757         unlockSystemUser();
1758         when(mMockContext.createPackageContextAsUser(
1759                  anyString(), anyInt(), any(UserHandle.class))).thenReturn(mMockContext);
1760         when(mMockContext.getPackageManager()).thenReturn(mMockPackageManager);
1761         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
1762         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
1763         final CountDownLatch latch = new CountDownLatch(1);
1764         Response response = new Response(latch, mMockAccountManagerResponse);
1765         mAms.getAuthToken(
1766                     response, // response
1767                     AccountManagerServiceTestFixtures.ACCOUNT_ERROR,
1768                     "authTokenType", // authTokenType
1769                     true, // notifyOnAuthFailure
1770                     false, // expectActivityLaunch
1771                     createGetAuthTokenOptions());
1772         waitForLatch(latch);
1773         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
1774                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
1775         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1776 
1777     }
1778 
1779     @SmallTest
testAddAccountAsUserWithNullResponse()1780     public void testAddAccountAsUserWithNullResponse() throws Exception {
1781         unlockSystemUser();
1782         try {
1783             mAms.addAccountAsUser(
1784                 null, // response
1785                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
1786                 "authTokenType",
1787                 null, // requiredFeatures
1788                 true, // expectActivityLaunch
1789                 null, // optionsIn
1790                 UserHandle.USER_SYSTEM);
1791             fail("IllegalArgumentException expected. But no exception was thrown.");
1792         } catch (IllegalArgumentException e) {
1793             // IllegalArgumentException is expected.
1794         }
1795     }
1796 
1797     @SmallTest
testAddAccountAsUserWithNullAccountType()1798     public void testAddAccountAsUserWithNullAccountType() throws Exception {
1799         unlockSystemUser();
1800         try {
1801             mAms.addAccountAsUser(
1802                 mMockAccountManagerResponse, // response
1803                 null, // accountType
1804                 "authTokenType",
1805                 null, // requiredFeatures
1806                 true, // expectActivityLaunch
1807                 null, // optionsIn
1808                 UserHandle.USER_SYSTEM);
1809             fail("IllegalArgumentException expected. But no exception was thrown.");
1810         } catch (IllegalArgumentException e) {
1811             // IllegalArgumentException is expected.
1812         }
1813     }
1814 
1815     @SmallTest
testAddAccountAsUserUserCannotModifyAccountNoDPM()1816     public void testAddAccountAsUserUserCannotModifyAccountNoDPM() throws Exception {
1817         unlockSystemUser();
1818         Bundle bundle = new Bundle();
1819         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
1820         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
1821         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
1822 
1823         mAms.addAccountAsUser(
1824                 mMockAccountManagerResponse, // response
1825                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1826                 "authTokenType",
1827                 null, // requiredFeatures
1828                 true, // expectActivityLaunch
1829                 null, // optionsIn
1830                 UserHandle.USER_SYSTEM);
1831         verify(mMockAccountManagerResponse).onError(
1832                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
1833         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
1834 
1835         // verify the intent for default CantAddAccountActivity is sent.
1836         Intent intent = mIntentCaptor.getValue();
1837         assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName());
1838         assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0),
1839                 AccountManager.ERROR_CODE_USER_RESTRICTED);
1840     }
1841 
1842     @SmallTest
testAddAccountAsUserUserCannotModifyAccountWithDPM()1843     public void testAddAccountAsUserUserCannotModifyAccountWithDPM() throws Exception {
1844         unlockSystemUser();
1845         Bundle bundle = new Bundle();
1846         bundle.putBoolean(UserManager.DISALLOW_MODIFY_ACCOUNTS, true);
1847         when(mMockUserManager.getUserRestrictions(any(UserHandle.class))).thenReturn(bundle);
1848         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
1849         LocalServices.addService(
1850                 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal);
1851         when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent(
1852                 anyInt(), anyString())).thenReturn(new Intent());
1853         when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent(
1854                 anyInt(), anyBoolean())).thenReturn(new Intent());
1855 
1856         mAms.addAccountAsUser(
1857                 mMockAccountManagerResponse, // response
1858                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1859                 "authTokenType",
1860                 null, // requiredFeatures
1861                 true, // expectActivityLaunch
1862                 null, // optionsIn
1863                 UserHandle.USER_SYSTEM);
1864 
1865         verify(mMockAccountManagerResponse).onError(
1866                 eq(AccountManager.ERROR_CODE_USER_RESTRICTED), anyString());
1867         verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM));
1868         verify(mMockDevicePolicyManagerInternal).createUserRestrictionSupportIntent(
1869                 anyInt(), anyString());
1870     }
1871 
1872     @SmallTest
testAddAccountAsUserUserCannotModifyAccountForTypeNoDPM()1873     public void testAddAccountAsUserUserCannotModifyAccountForTypeNoDPM() throws Exception {
1874         unlockSystemUser();
1875         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
1876                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
1877         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
1878 
1879         mAms.addAccountAsUser(
1880                 mMockAccountManagerResponse, // response
1881                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1882                 "authTokenType",
1883                 null, // requiredFeatures
1884                 true, // expectActivityLaunch
1885                 null, // optionsIn
1886                 UserHandle.USER_SYSTEM);
1887 
1888         verify(mMockAccountManagerResponse).onError(
1889                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
1890         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
1891 
1892         // verify the intent for default CantAddAccountActivity is sent.
1893         Intent intent = mIntentCaptor.getValue();
1894         assertEquals(intent.getComponent().getClassName(), CantAddAccountActivity.class.getName());
1895         assertEquals(intent.getIntExtra(CantAddAccountActivity.EXTRA_ERROR_CODE, 0),
1896                 AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE);
1897     }
1898 
1899     @SmallTest
testAddAccountAsUserUserCannotModifyAccountForTypeWithDPM()1900     public void testAddAccountAsUserUserCannotModifyAccountForTypeWithDPM() throws Exception {
1901         unlockSystemUser();
1902         when(mMockContext.getSystemService(Context.DEVICE_POLICY_SERVICE)).thenReturn(
1903                 mMockDevicePolicyManager);
1904         when(mMockDevicePolicyManager.getAccountTypesWithManagementDisabledAsUser(anyInt()))
1905                 .thenReturn(new String[]{AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, "BBB"});
1906 
1907         LocalServices.removeServiceForTest(DevicePolicyManagerInternal.class);
1908         LocalServices.addService(
1909                 DevicePolicyManagerInternal.class, mMockDevicePolicyManagerInternal);
1910         when(mMockDevicePolicyManagerInternal.createUserRestrictionSupportIntent(
1911                 anyInt(), anyString())).thenReturn(new Intent());
1912         when(mMockDevicePolicyManagerInternal.createShowAdminSupportIntent(
1913                 anyInt(), anyBoolean())).thenReturn(new Intent());
1914 
1915         mAms.addAccountAsUser(
1916                 mMockAccountManagerResponse, // response
1917                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1918                 "authTokenType",
1919                 null, // requiredFeatures
1920                 true, // expectActivityLaunch
1921                 null, // optionsIn
1922                 UserHandle.USER_SYSTEM);
1923 
1924         verify(mMockAccountManagerResponse).onError(
1925                 eq(AccountManager.ERROR_CODE_MANAGEMENT_DISABLED_FOR_ACCOUNT_TYPE), anyString());
1926         verify(mMockContext).startActivityAsUser(any(Intent.class), eq(UserHandle.SYSTEM));
1927         verify(mMockDevicePolicyManagerInternal).createShowAdminSupportIntent(
1928                 anyInt(), anyBoolean());
1929     }
1930 
1931     @SmallTest
testAddAccountAsUserSuccess()1932     public void testAddAccountAsUserSuccess() throws Exception {
1933         unlockSystemUser();
1934         final CountDownLatch latch = new CountDownLatch(1);
1935         Response response = new Response(latch, mMockAccountManagerResponse);
1936         mAms.addAccountAsUser(
1937                 response, // response
1938                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1939                 "authTokenType",
1940                 null, // requiredFeatures
1941                 true, // expectActivityLaunch
1942                 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS),
1943                 UserHandle.USER_SYSTEM);
1944         waitForLatch(latch);
1945         // Verify notification is cancelled
1946         verify(mMockNotificationManager).cancelNotificationWithTag(
1947                 anyString(), nullable(String.class), anyInt(), anyInt());
1948 
1949         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
1950         Bundle result = mBundleCaptor.getValue();
1951         // Verify response data
1952         assertNull(result.getString(AccountManager.KEY_AUTHTOKEN, null));
1953         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS,
1954                 result.getString(AccountManager.KEY_ACCOUNT_NAME));
1955         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
1956                 result.getString(AccountManager.KEY_ACCOUNT_TYPE));
1957 
1958         Bundle optionBundle = result.getParcelable(
1959                 AccountManagerServiceTestFixtures.KEY_OPTIONS_BUNDLE);
1960         // Assert addAccountAsUser added calling uid and pid into the option bundle
1961         assertTrue(optionBundle.containsKey(AccountManager.KEY_CALLER_UID));
1962         assertTrue(optionBundle.containsKey(AccountManager.KEY_CALLER_PID));
1963     }
1964 
1965     @SmallTest
testAddAccountAsUserReturnWithInvalidIntent()1966     public void testAddAccountAsUserReturnWithInvalidIntent() throws Exception {
1967         unlockSystemUser();
1968         ResolveInfo resolveInfo = new ResolveInfo();
1969         resolveInfo.activityInfo = new ActivityInfo();
1970         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
1971         when(mMockPackageManager.resolveActivityAsUser(
1972                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
1973         when(mMockPackageManager.checkSignatures(
1974                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
1975         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
1976                 .thenReturn(false);
1977 
1978         final CountDownLatch latch = new CountDownLatch(1);
1979         Response response = new Response(latch, mMockAccountManagerResponse);
1980         mAms.addAccountAsUser(
1981                 response, // response
1982                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
1983                 "authTokenType",
1984                 null, // requiredFeatures
1985                 true, // expectActivityLaunch
1986                 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE),
1987                 UserHandle.USER_SYSTEM);
1988 
1989         waitForLatch(latch);
1990         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
1991         verify(mMockAccountManagerResponse).onError(
1992                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
1993     }
1994 
1995     @SmallTest
testAddAccountAsUserReturnWithValidIntent()1996     public void testAddAccountAsUserReturnWithValidIntent() throws Exception {
1997         unlockSystemUser();
1998         ResolveInfo resolveInfo = new ResolveInfo();
1999         resolveInfo.activityInfo = new ActivityInfo();
2000         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
2001         when(mMockPackageManager.resolveActivityAsUser(
2002                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
2003         when(mMockPackageManager.checkSignatures(
2004                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
2005 
2006         final CountDownLatch latch = new CountDownLatch(1);
2007         Response response = new Response(latch, mMockAccountManagerResponse);
2008 
2009         mAms.addAccountAsUser(
2010                 response, // response
2011                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
2012                 "authTokenType",
2013                 null, // requiredFeatures
2014                 true, // expectActivityLaunch
2015                 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_INTERVENE),
2016                 UserHandle.USER_SYSTEM);
2017 
2018         waitForLatch(latch);
2019 
2020         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2021         Bundle result = mBundleCaptor.getValue();
2022         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
2023         assertNotNull(intent);
2024         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
2025         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
2026     }
2027 
2028     @SmallTest
testAddAccountAsUserError()2029     public void testAddAccountAsUserError() throws Exception {
2030         unlockSystemUser();
2031 
2032         final CountDownLatch latch = new CountDownLatch(1);
2033         Response response = new Response(latch, mMockAccountManagerResponse);
2034 
2035         mAms.addAccountAsUser(
2036                 response, // response
2037                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
2038                 "authTokenType",
2039                 null, // requiredFeatures
2040                 true, // expectActivityLaunch
2041                 createAddAccountOptions(AccountManagerServiceTestFixtures.ACCOUNT_NAME_ERROR),
2042                 UserHandle.USER_SYSTEM);
2043 
2044         waitForLatch(latch);
2045         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2046                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
2047         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
2048     }
2049 
2050     @SmallTest
testConfirmCredentialsAsUserWithNullResponse()2051     public void testConfirmCredentialsAsUserWithNullResponse() throws Exception {
2052         unlockSystemUser();
2053         try {
2054             mAms.confirmCredentialsAsUser(
2055                 null, // response
2056                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
2057                 new Bundle(), // options
2058                 false, // expectActivityLaunch
2059                 UserHandle.USER_SYSTEM);
2060             fail("IllegalArgumentException expected. But no exception was thrown.");
2061         } catch (IllegalArgumentException e) {
2062             // IllegalArgumentException is expected.
2063         }
2064     }
2065 
2066     @SmallTest
testConfirmCredentialsAsUserWithNullAccount()2067     public void testConfirmCredentialsAsUserWithNullAccount() throws Exception {
2068         unlockSystemUser();
2069         try {
2070             mAms.confirmCredentialsAsUser(
2071                 mMockAccountManagerResponse, // response
2072                 null, // account
2073                 new Bundle(), // options
2074                 false, // expectActivityLaunch
2075                 UserHandle.USER_SYSTEM);
2076             fail("IllegalArgumentException expected. But no exception was thrown.");
2077         } catch (IllegalArgumentException e) {
2078             // IllegalArgumentException is expected.
2079         }
2080     }
2081 
2082     @SmallTest
testConfirmCredentialsAsUserSuccess()2083     public void testConfirmCredentialsAsUserSuccess() throws Exception {
2084         unlockSystemUser();
2085         final CountDownLatch latch = new CountDownLatch(1);
2086         Response response = new Response(latch, mMockAccountManagerResponse);
2087         mAms.confirmCredentialsAsUser(
2088                 response, // response
2089                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
2090                 new Bundle(), // options
2091                 true, // expectActivityLaunch
2092                 UserHandle.USER_SYSTEM);
2093         waitForLatch(latch);
2094 
2095         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2096         Bundle result = mBundleCaptor.getValue();
2097         // Verify response data
2098         assertTrue(result.getBoolean(AccountManager.KEY_BOOLEAN_RESULT));
2099         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS,
2100                 result.getString(AccountManager.KEY_ACCOUNT_NAME));
2101         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2102                 result.getString(AccountManager.KEY_ACCOUNT_TYPE));
2103     }
2104 
2105     @SmallTest
testConfirmCredentialsAsUserReturnWithInvalidIntent()2106     public void testConfirmCredentialsAsUserReturnWithInvalidIntent() throws Exception {
2107         unlockSystemUser();
2108         ResolveInfo resolveInfo = new ResolveInfo();
2109         resolveInfo.activityInfo = new ActivityInfo();
2110         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
2111         when(mMockPackageManager.resolveActivityAsUser(
2112                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
2113         when(mMockPackageManager.checkSignatures(
2114                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
2115         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
2116                 .thenReturn(false);
2117 
2118         final CountDownLatch latch = new CountDownLatch(1);
2119         Response response = new Response(latch, mMockAccountManagerResponse);
2120         mAms.confirmCredentialsAsUser(
2121                 response, // response
2122                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
2123                 new Bundle(), // options
2124                 true, // expectActivityLaunch
2125                 UserHandle.USER_SYSTEM);
2126         waitForLatch(latch);
2127 
2128         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
2129         verify(mMockAccountManagerResponse).onError(
2130                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
2131     }
2132 
2133     @SmallTest
testConfirmCredentialsAsUserReturnWithValidIntent()2134     public void testConfirmCredentialsAsUserReturnWithValidIntent() throws Exception {
2135         unlockSystemUser();
2136         ResolveInfo resolveInfo = new ResolveInfo();
2137         resolveInfo.activityInfo = new ActivityInfo();
2138         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
2139         when(mMockPackageManager.resolveActivityAsUser(
2140                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
2141         when(mMockPackageManager.checkSignatures(
2142                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
2143 
2144         final CountDownLatch latch = new CountDownLatch(1);
2145         Response response = new Response(latch, mMockAccountManagerResponse);
2146 
2147         mAms.confirmCredentialsAsUser(
2148                 response, // response
2149                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
2150                 new Bundle(), // options
2151                 true, // expectActivityLaunch
2152                 UserHandle.USER_SYSTEM);
2153 
2154         waitForLatch(latch);
2155 
2156         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2157         Bundle result = mBundleCaptor.getValue();
2158         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
2159         assertNotNull(intent);
2160         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
2161         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
2162     }
2163 
2164     @SmallTest
testConfirmCredentialsAsUserError()2165     public void testConfirmCredentialsAsUserError() throws Exception {
2166         unlockSystemUser();
2167 
2168         final CountDownLatch latch = new CountDownLatch(1);
2169         Response response = new Response(latch, mMockAccountManagerResponse);
2170 
2171         mAms.confirmCredentialsAsUser(
2172                 response, // response
2173                 AccountManagerServiceTestFixtures.ACCOUNT_ERROR,
2174                 new Bundle(), // options
2175                 true, // expectActivityLaunch
2176                 UserHandle.USER_SYSTEM);
2177 
2178         waitForLatch(latch);
2179         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2180                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
2181         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
2182     }
2183 
2184     @SmallTest
testUpdateCredentialsWithNullResponse()2185     public void testUpdateCredentialsWithNullResponse() throws Exception {
2186         unlockSystemUser();
2187         try {
2188             mAms.updateCredentials(
2189                 null, // response
2190                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
2191                 "authTokenType",
2192                 false, // expectActivityLaunch
2193                 new Bundle()); // options
2194             fail("IllegalArgumentException expected. But no exception was thrown.");
2195         } catch (IllegalArgumentException e) {
2196             // IllegalArgumentException is expected.
2197         }
2198     }
2199 
2200     @SmallTest
testUpdateCredentialsWithNullAccount()2201     public void testUpdateCredentialsWithNullAccount() throws Exception {
2202         unlockSystemUser();
2203         try {
2204             mAms.updateCredentials(
2205                 mMockAccountManagerResponse, // response
2206                 null, // account
2207                 "authTokenType",
2208                 false, // expectActivityLaunch
2209                 new Bundle()); // options
2210             fail("IllegalArgumentException expected. But no exception was thrown.");
2211         } catch (IllegalArgumentException e) {
2212             // IllegalArgumentException is expected.
2213         }
2214     }
2215 
2216     @SmallTest
testUpdateCredentialsSuccess()2217     public void testUpdateCredentialsSuccess() throws Exception {
2218         unlockSystemUser();
2219         final CountDownLatch latch = new CountDownLatch(1);
2220         Response response = new Response(latch, mMockAccountManagerResponse);
2221 
2222         mAms.updateCredentials(
2223                 response, // response
2224                 AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS,
2225                 "authTokenType",
2226                 false, // expectActivityLaunch
2227                 new Bundle()); // options
2228 
2229         waitForLatch(latch);
2230 
2231         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2232         Bundle result = mBundleCaptor.getValue();
2233         // Verify response data
2234         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS,
2235                 result.getString(AccountManager.KEY_ACCOUNT_NAME));
2236         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2237                 result.getString(AccountManager.KEY_ACCOUNT_TYPE));
2238     }
2239 
2240     @SmallTest
testUpdateCredentialsReturnWithInvalidIntent()2241     public void testUpdateCredentialsReturnWithInvalidIntent() throws Exception {
2242         unlockSystemUser();
2243         ResolveInfo resolveInfo = new ResolveInfo();
2244         resolveInfo.activityInfo = new ActivityInfo();
2245         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
2246         when(mMockPackageManager.resolveActivityAsUser(
2247                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
2248         when(mMockPackageManager.checkSignatures(
2249                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_NO_MATCH);
2250         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
2251                 .thenReturn(false);
2252 
2253         final CountDownLatch latch = new CountDownLatch(1);
2254         Response response = new Response(latch, mMockAccountManagerResponse);
2255 
2256         mAms.updateCredentials(
2257                 response, // response
2258                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
2259                 "authTokenType",
2260                 true, // expectActivityLaunch
2261                 new Bundle()); // options
2262 
2263         waitForLatch(latch);
2264 
2265         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
2266         verify(mMockAccountManagerResponse).onError(
2267                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
2268     }
2269 
2270     @SmallTest
testUpdateCredentialsReturnWithValidIntent()2271     public void testUpdateCredentialsReturnWithValidIntent() throws Exception {
2272         unlockSystemUser();
2273         ResolveInfo resolveInfo = new ResolveInfo();
2274         resolveInfo.activityInfo = new ActivityInfo();
2275         resolveInfo.activityInfo.applicationInfo = new ApplicationInfo();
2276         when(mMockPackageManager.resolveActivityAsUser(
2277                 any(Intent.class), anyInt(), anyInt())).thenReturn(resolveInfo);
2278         when(mMockPackageManager.checkSignatures(
2279                 anyInt(), anyInt())).thenReturn(PackageManager.SIGNATURE_MATCH);
2280 
2281         final CountDownLatch latch = new CountDownLatch(1);
2282         Response response = new Response(latch, mMockAccountManagerResponse);
2283 
2284         mAms.updateCredentials(
2285                 response, // response
2286                 AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE,
2287                 "authTokenType",
2288                 true, // expectActivityLaunch
2289                 new Bundle()); // options
2290 
2291         waitForLatch(latch);
2292 
2293         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2294         Bundle result = mBundleCaptor.getValue();
2295         Intent intent = result.getParcelable(AccountManager.KEY_INTENT);
2296         assertNotNull(intent);
2297         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_RESULT));
2298         assertNotNull(intent.getParcelableExtra(AccountManagerServiceTestFixtures.KEY_CALLBACK));
2299     }
2300 
2301     @SmallTest
testUpdateCredentialsError()2302     public void testUpdateCredentialsError() throws Exception {
2303         unlockSystemUser();
2304 
2305         final CountDownLatch latch = new CountDownLatch(1);
2306         Response response = new Response(latch, mMockAccountManagerResponse);
2307 
2308         mAms.updateCredentials(
2309                 response, // response
2310                 AccountManagerServiceTestFixtures.ACCOUNT_ERROR,
2311                 "authTokenType",
2312                 false, // expectActivityLaunch
2313                 new Bundle()); // options
2314 
2315         waitForLatch(latch);
2316         verify(mMockAccountManagerResponse).onError(AccountManager.ERROR_CODE_INVALID_RESPONSE,
2317                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
2318         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
2319     }
2320 
2321     @SmallTest
testEditPropertiesWithNullResponse()2322     public void testEditPropertiesWithNullResponse() throws Exception {
2323         unlockSystemUser();
2324         try {
2325             mAms.editProperties(
2326                 null, // response
2327                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2328                 false); // expectActivityLaunch
2329             fail("IllegalArgumentException expected. But no exception was thrown.");
2330         } catch (IllegalArgumentException e) {
2331             // IllegalArgumentException is expected.
2332         }
2333     }
2334 
2335     @SmallTest
testEditPropertiesWithNullAccountType()2336     public void testEditPropertiesWithNullAccountType() throws Exception {
2337         unlockSystemUser();
2338         try {
2339             mAms.editProperties(
2340                 mMockAccountManagerResponse, // response
2341                 null, // accountType
2342                 false); // expectActivityLaunch
2343             fail("IllegalArgumentException expected. But no exception was thrown.");
2344         } catch (IllegalArgumentException e) {
2345             // IllegalArgumentException is expected.
2346         }
2347     }
2348 
2349     @SmallTest
testEditPropertiesAccountNotManagedByCaller()2350     public void testEditPropertiesAccountNotManagedByCaller() throws Exception {
2351         unlockSystemUser();
2352         when(mMockPackageManager.checkSignatures(anyInt(), anyInt()))
2353                     .thenReturn(PackageManager.SIGNATURE_NO_MATCH);
2354         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
2355                 .thenReturn(false);
2356         try {
2357             mAms.editProperties(
2358                 mMockAccountManagerResponse, // response
2359                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2360                 false); // expectActivityLaunch
2361             fail("SecurityException expected. But no exception was thrown.");
2362         } catch (SecurityException e) {
2363             // SecurityException is expected.
2364         }
2365     }
2366 
2367     @SmallTest
testEditPropertiesSuccess()2368     public void testEditPropertiesSuccess() throws Exception {
2369         unlockSystemUser();
2370         final CountDownLatch latch = new CountDownLatch(1);
2371         Response response = new Response(latch, mMockAccountManagerResponse);
2372 
2373         mAms.editProperties(
2374                 response, // response
2375                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2376                 false); // expectActivityLaunch
2377 
2378         waitForLatch(latch);
2379 
2380         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2381         Bundle result = mBundleCaptor.getValue();
2382         // Verify response data
2383         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS,
2384                 result.getString(AccountManager.KEY_ACCOUNT_NAME));
2385         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2386                 result.getString(AccountManager.KEY_ACCOUNT_TYPE));
2387     }
2388 
2389     @SmallTest
testGetAccountByTypeAndFeaturesWithNullResponse()2390     public void testGetAccountByTypeAndFeaturesWithNullResponse() throws Exception {
2391         unlockSystemUser();
2392         try {
2393             mAms.getAccountByTypeAndFeatures(
2394                 null, // response
2395                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2396                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2397                 "testpackage"); // opPackageName
2398             fail("IllegalArgumentException expected. But no exception was thrown.");
2399         } catch (IllegalArgumentException e) {
2400             // IllegalArgumentException is expected.
2401         }
2402     }
2403 
2404     @SmallTest
testGetAccountByTypeAndFeaturesWithNullAccountType()2405     public void testGetAccountByTypeAndFeaturesWithNullAccountType() throws Exception {
2406         unlockSystemUser();
2407         try {
2408             mAms.getAccountByTypeAndFeatures(
2409                 mMockAccountManagerResponse, // response
2410                 null, // accountType
2411                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2412                 "testpackage"); // opPackageName
2413             fail("IllegalArgumentException expected. But no exception was thrown.");
2414         } catch (IllegalArgumentException e) {
2415             // IllegalArgumentException is expected.
2416         }
2417     }
2418 
2419     @SmallTest
testGetAccountByTypeAndFeaturesWithNoFeaturesAndNoAccount()2420     public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndNoAccount() throws Exception {
2421         unlockSystemUser();
2422         mAms.getAccountByTypeAndFeatures(
2423             mMockAccountManagerResponse,
2424             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2425             null,
2426             "testpackage");
2427         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2428         Bundle result = mBundleCaptor.getValue();
2429         String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2430         String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2431         assertEquals(null, accountName);
2432         assertEquals(null, accountType);
2433     }
2434 
2435     @SmallTest
testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneVisibleAccount()2436     public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneVisibleAccount()
2437         throws Exception {
2438         unlockSystemUser();
2439         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2440         mAms.getAccountByTypeAndFeatures(
2441             mMockAccountManagerResponse,
2442             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2443             null,
2444             "testpackage");
2445         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2446         Bundle result = mBundleCaptor.getValue();
2447         String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2448         String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2449         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, accountName);
2450         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, accountType);
2451     }
2452 
2453     @SmallTest
testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneNotVisibleAccount()2454     public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndOneNotVisibleAccount()
2455         throws Exception {
2456         unlockSystemUser();
2457         HashMap<String, Integer> visibility = new HashMap<>();
2458         visibility.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE,
2459             AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE);
2460         mAms.addAccountExplicitlyWithVisibility(
2461             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility);
2462         mAms.getAccountByTypeAndFeatures(
2463             mMockAccountManagerResponse,
2464             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2465             null,
2466             AccountManagerServiceTestFixtures.CALLER_PACKAGE);
2467         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
2468         Intent intent = mIntentCaptor.getValue();
2469         Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS);
2470         assertEquals(1, accounts.length);
2471         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]);
2472     }
2473 
2474     @SmallTest
testGetAccountByTypeAndFeaturesWithNoFeaturesAndTwoAccounts()2475     public void testGetAccountByTypeAndFeaturesWithNoFeaturesAndTwoAccounts() throws Exception {
2476         unlockSystemUser();
2477         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2478         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null);
2479 
2480         mAms.getAccountByTypeAndFeatures(
2481             mMockAccountManagerResponse,
2482             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2483             null,
2484             "testpackage");
2485         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
2486         Intent intent = mIntentCaptor.getValue();
2487         Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS);
2488         assertEquals(2, accounts.length);
2489         if (accounts[0].equals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS)) {
2490             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]);
2491             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, accounts[1]);
2492         } else {
2493             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, accounts[0]);
2494             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[1]);
2495         }
2496     }
2497 
2498     @SmallTest
testGetAccountByTypeAndFeaturesWithFeaturesAndNoAccount()2499     public void testGetAccountByTypeAndFeaturesWithFeaturesAndNoAccount() throws Exception {
2500         unlockSystemUser();
2501         final CountDownLatch latch = new CountDownLatch(1);
2502         mAms.getAccountByTypeAndFeatures(
2503             mMockAccountManagerResponse,
2504             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2505             AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2506             "testpackage");
2507         waitForLatch(latch);
2508         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2509         Bundle result = mBundleCaptor.getValue();
2510         String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2511         String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2512         assertEquals(null, accountName);
2513         assertEquals(null, accountType);
2514     }
2515 
2516     @SmallTest
testGetAccountByTypeAndFeaturesWithFeaturesAndNoQualifiedAccount()2517     public void testGetAccountByTypeAndFeaturesWithFeaturesAndNoQualifiedAccount()
2518         throws Exception {
2519         unlockSystemUser();
2520         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null);
2521         final CountDownLatch latch = new CountDownLatch(1);
2522         mAms.getAccountByTypeAndFeatures(
2523             mMockAccountManagerResponse,
2524             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2525             AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2526             "testpackage");
2527         waitForLatch(latch);
2528         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2529         Bundle result = mBundleCaptor.getValue();
2530         String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2531         String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2532         assertEquals(null, accountName);
2533         assertEquals(null, accountType);
2534     }
2535 
2536     @SmallTest
testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedAccount()2537     public void testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedAccount()
2538         throws Exception {
2539         unlockSystemUser();
2540         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2541         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null);
2542         final CountDownLatch latch = new CountDownLatch(1);
2543         mAms.getAccountByTypeAndFeatures(
2544             mMockAccountManagerResponse,
2545             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2546             AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2547             "testpackage");
2548         waitForLatch(latch);
2549         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2550         Bundle result = mBundleCaptor.getValue();
2551         String accountName = result.getString(AccountManager.KEY_ACCOUNT_NAME);
2552         String accountType = result.getString(AccountManager.KEY_ACCOUNT_TYPE);
2553         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_NAME_SUCCESS, accountName);
2554         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, accountType);
2555     }
2556 
2557     @SmallTest
testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedNotVisibleAccount()2558     public void testGetAccountByTypeAndFeaturesWithFeaturesAndOneQualifiedNotVisibleAccount()
2559         throws Exception {
2560         unlockSystemUser();
2561         HashMap<String, Integer> visibility = new HashMap<>();
2562         visibility.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE,
2563             AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE);
2564         mAms.addAccountExplicitlyWithVisibility(
2565             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility);
2566         final CountDownLatch latch = new CountDownLatch(1);
2567         mAms.getAccountByTypeAndFeatures(
2568             mMockAccountManagerResponse,
2569             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2570             AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2571             AccountManagerServiceTestFixtures.CALLER_PACKAGE);
2572         waitForLatch(latch);
2573         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
2574         Intent intent = mIntentCaptor.getValue();
2575         Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS);
2576         assertEquals(1, accounts.length);
2577         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]);
2578     }
2579 
2580     @SmallTest
testGetAccountByTypeAndFeaturesWithFeaturesAndTwoQualifiedAccount()2581     public void testGetAccountByTypeAndFeaturesWithFeaturesAndTwoQualifiedAccount()
2582         throws Exception {
2583         unlockSystemUser();
2584         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2585         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_2, "p12", null);
2586         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p13", null);
2587         final CountDownLatch latch = new CountDownLatch(1);
2588         mAms.getAccountByTypeAndFeatures(
2589             mMockAccountManagerResponse,
2590             AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2591             AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2592             "testpackage");
2593         waitForLatch(latch);
2594         verify(mMockContext).startActivityAsUser(mIntentCaptor.capture(), eq(UserHandle.SYSTEM));
2595         Intent intent = mIntentCaptor.getValue();
2596         Account[] accounts = (Account[]) intent.getExtra(AccountManager.KEY_ACCOUNTS);
2597         assertEquals(2, accounts.length);
2598         if (accounts[0].equals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS)) {
2599             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]);
2600             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_2, accounts[1]);
2601         } else {
2602             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_2, accounts[0]);
2603             assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[1]);
2604         }
2605     }
2606 
2607     @SmallTest
testGetAccountsByFeaturesWithNullResponse()2608     public void testGetAccountsByFeaturesWithNullResponse() throws Exception {
2609         unlockSystemUser();
2610         try {
2611             mAms.getAccountsByFeatures(
2612                 null, // response
2613                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1,
2614                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2615                 "testpackage"); // opPackageName
2616             fail("IllegalArgumentException expected. But no exception was thrown.");
2617         } catch (IllegalArgumentException e) {
2618             // IllegalArgumentException is expected.
2619         }
2620     }
2621 
2622     @SmallTest
testGetAccountsByFeaturesWithNullAccountType()2623     public void testGetAccountsByFeaturesWithNullAccountType() throws Exception {
2624         unlockSystemUser();
2625         try {
2626             mAms.getAccountsByFeatures(
2627                 mMockAccountManagerResponse, // response
2628                 null, // accountType
2629                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2630                 "testpackage"); // opPackageName
2631             fail("IllegalArgumentException expected. But no exception was thrown.");
2632         } catch (IllegalArgumentException e) {
2633             // IllegalArgumentException is expected.
2634         }
2635     }
2636 
2637     @SmallTest
testGetAccountsByFeaturesAccountNotVisible()2638     public void testGetAccountsByFeaturesAccountNotVisible() throws Exception {
2639         unlockSystemUser();
2640 
2641         when(mMockContext.checkCallingOrSelfPermission(anyString())).thenReturn(
2642                 PackageManager.PERMISSION_DENIED);
2643         when(mMockPackageManager.checkSignatures(anyInt(), anyInt()))
2644                     .thenReturn(PackageManager.SIGNATURE_NO_MATCH);
2645         when(mMockPackageManagerInternal.hasSignatureCapability(anyInt(), anyInt(), anyInt()))
2646                 .thenReturn(false);
2647 
2648         final CountDownLatch latch = new CountDownLatch(1);
2649         Response response = new Response(latch, mMockAccountManagerResponse);
2650         mAms.getAccountsByFeatures(
2651                 response, // response
2652                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
2653                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2654                 "testpackage"); // opPackageName
2655         waitForLatch(latch);
2656 
2657         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2658         Bundle result = mBundleCaptor.getValue();
2659         Account[] accounts = (Account[]) result.getParcelableArray(AccountManager.KEY_ACCOUNTS);
2660         assertTrue(accounts.length == 0);
2661     }
2662 
2663     @SmallTest
testGetAccountsByFeaturesNullFeatureReturnsAllAccounts()2664     public void testGetAccountsByFeaturesNullFeatureReturnsAllAccounts() throws Exception {
2665         unlockSystemUser();
2666 
2667         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2668         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null);
2669 
2670         final CountDownLatch latch = new CountDownLatch(1);
2671         Response response = new Response(latch, mMockAccountManagerResponse);
2672         mAms.getAccountsByFeatures(
2673                 response, // response
2674                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
2675                 null, // features
2676                 "testpackage"); // opPackageName
2677         waitForLatch(latch);
2678 
2679         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2680         Bundle result = mBundleCaptor.getValue();
2681         Account[] accounts = (Account[]) result.getParcelableArray(AccountManager.KEY_ACCOUNTS);
2682         Arrays.sort(accounts, new AccountSorter());
2683         assertEquals(2, accounts.length);
2684         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, accounts[0]);
2685         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[1]);
2686     }
2687 
2688     @SmallTest
testGetAccountsByFeaturesReturnsAccountsWithFeaturesOnly()2689     public void testGetAccountsByFeaturesReturnsAccountsWithFeaturesOnly() throws Exception {
2690         unlockSystemUser();
2691 
2692         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2693         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p12", null);
2694 
2695         final CountDownLatch latch = new CountDownLatch(1);
2696         Response response = new Response(latch, mMockAccountManagerResponse);
2697         mAms.getAccountsByFeatures(
2698                 response, // response
2699                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
2700                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2701                 "testpackage"); // opPackageName
2702         waitForLatch(latch);
2703 
2704         verify(mMockAccountManagerResponse).onResult(mBundleCaptor.capture());
2705         Bundle result = mBundleCaptor.getValue();
2706         Account[] accounts = (Account[]) result.getParcelableArray(AccountManager.KEY_ACCOUNTS);
2707         assertEquals(1, accounts.length);
2708         assertEquals(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, accounts[0]);
2709     }
2710 
2711     @SmallTest
testGetAccountsByFeaturesError()2712     public void testGetAccountsByFeaturesError() throws Exception {
2713         unlockSystemUser();
2714         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2715         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_ERROR, "p12", null);
2716 
2717         final CountDownLatch latch = new CountDownLatch(1);
2718         Response response = new Response(latch, mMockAccountManagerResponse);
2719         mAms.getAccountsByFeatures(
2720                 response, // response
2721                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1, // accountType
2722                 AccountManagerServiceTestFixtures.ACCOUNT_FEATURES,
2723                 "testpackage"); // opPackageName
2724         waitForLatch(latch);
2725 
2726         verify(mMockAccountManagerResponse).onError(
2727                 eq(AccountManager.ERROR_CODE_INVALID_RESPONSE), anyString());
2728         verify(mMockAccountManagerResponse, never()).onResult(any(Bundle.class));
2729     }
2730 
2731     @SmallTest
testRegisterAccountListener()2732     public void testRegisterAccountListener() throws Exception {
2733         unlockSystemUser();
2734         mAms.registerAccountListener(
2735             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2736             "testpackage"); // opPackageName
2737 
2738         mAms.registerAccountListener(
2739             null, //accountTypes
2740             "testpackage"); // opPackageName
2741 
2742         // Check that two previously registered receivers can be unregistered successfully.
2743         mAms.unregisterAccountListener(
2744             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2745             "testpackage"); // opPackageName
2746 
2747         mAms.unregisterAccountListener(
2748              null, //accountTypes
2749             "testpackage"); // opPackageName
2750     }
2751 
2752     @SmallTest
testRegisterAccountListenerAndAddAccount()2753     public void testRegisterAccountListenerAndAddAccount() throws Exception {
2754         unlockSystemUser();
2755         mAms.registerAccountListener(
2756             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2757             "testpackage"); // opPackageName
2758 
2759         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2760         // Notification about new account
2761         updateBroadcastCounters(2);
2762         assertEquals(mVisibleAccountsChangedBroadcasts, 1);
2763         assertEquals(mLoginAccountsChangedBroadcasts, 1);
2764     }
2765 
2766     @SmallTest
testRegisterAccountListenerAndAddAccountOfDifferentType()2767     public void testRegisterAccountListenerAndAddAccountOfDifferentType() throws Exception {
2768         unlockSystemUser();
2769         mAms.registerAccountListener(
2770             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_2},
2771             "testpackage"); // opPackageName
2772 
2773         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2774         mAms.addAccountExplicitly(
2775             AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p11", null);
2776         // Notification about new account
2777 
2778         updateBroadcastCounters(2);
2779         assertEquals(mVisibleAccountsChangedBroadcasts, 0); // broadcast was not sent
2780         assertEquals(mLoginAccountsChangedBroadcasts, 2);
2781     }
2782 
2783     @SmallTest
testRegisterAccountListenerWithAddingTwoAccounts()2784     public void testRegisterAccountListenerWithAddingTwoAccounts() throws Exception {
2785         unlockSystemUser();
2786 
2787         HashMap<String, Integer> visibility = new HashMap<>();
2788         visibility.put(AccountManagerServiceTestFixtures.CALLER_PACKAGE,
2789             AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
2790 
2791         mAms.registerAccountListener(
2792             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2793             AccountManagerServiceTestFixtures.CALLER_PACKAGE);
2794         mAms.addAccountExplicitlyWithVisibility(
2795             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility);
2796         mAms.unregisterAccountListener(
2797             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2798             AccountManagerServiceTestFixtures.CALLER_PACKAGE);
2799 
2800         addAccountRemovedReceiver(AccountManagerServiceTestFixtures.CALLER_PACKAGE);
2801         mAms.addAccountExplicitlyWithVisibility(
2802             AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE, "p11", null, visibility);
2803 
2804         updateBroadcastCounters(3);
2805         assertEquals(mVisibleAccountsChangedBroadcasts, 1);
2806         assertEquals(mLoginAccountsChangedBroadcasts, 2);
2807         assertEquals(mAccountRemovedBroadcasts, 0);
2808 
2809         mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS);
2810         mAms.registerAccountListener( null /* accountTypes */,
2811             AccountManagerServiceTestFixtures.CALLER_PACKAGE);
2812         mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_INTERVENE);
2813 
2814         updateBroadcastCounters(8);
2815         assertEquals(mVisibleAccountsChangedBroadcasts, 2);
2816         assertEquals(mLoginAccountsChangedBroadcasts, 4);
2817         assertEquals(mAccountRemovedBroadcasts, 2);
2818     }
2819 
2820     @SmallTest
testRegisterAccountListenerForThreePackages()2821     public void testRegisterAccountListenerForThreePackages() throws Exception {
2822         unlockSystemUser();
2823 
2824         addAccountRemovedReceiver("testpackage1");
2825         HashMap<String, Integer> visibility = new HashMap<>();
2826         visibility.put("testpackage1", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
2827         visibility.put("testpackage2", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
2828         visibility.put("testpackage3", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
2829 
2830         mAms.registerAccountListener(
2831             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2832             "testpackage1"); // opPackageName
2833         mAms.registerAccountListener(
2834             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2835             "testpackage2"); // opPackageName
2836         mAms.registerAccountListener(
2837             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2838             "testpackage3"); // opPackageName
2839         mAms.addAccountExplicitlyWithVisibility(
2840             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility);
2841         updateBroadcastCounters(4);
2842         assertEquals(mVisibleAccountsChangedBroadcasts, 3);
2843         assertEquals(mLoginAccountsChangedBroadcasts, 1);
2844 
2845         mAms.unregisterAccountListener(
2846             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2847             "testpackage3"); // opPackageName
2848         // Remove account with 2 active listeners.
2849         mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS);
2850         updateBroadcastCounters(8);
2851         assertEquals(mVisibleAccountsChangedBroadcasts, 5);
2852         assertEquals(mLoginAccountsChangedBroadcasts, 2); // 3 add, 2 remove
2853         assertEquals(mAccountRemovedBroadcasts, 1);
2854 
2855         // Add account of another type.
2856         mAms.addAccountExplicitly(
2857             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS_TYPE_2, "p11", null);
2858 
2859         updateBroadcastCounters(8);
2860         assertEquals(mVisibleAccountsChangedBroadcasts, 5);
2861         assertEquals(mLoginAccountsChangedBroadcasts, 3);
2862         assertEquals(mAccountRemovedBroadcasts, 1);
2863     }
2864 
2865     @SmallTest
testRegisterAccountListenerForAddingAccountWithVisibility()2866     public void testRegisterAccountListenerForAddingAccountWithVisibility() throws Exception {
2867         unlockSystemUser();
2868 
2869         HashMap<String, Integer> visibility = new HashMap<>();
2870         visibility.put("testpackage1", AccountManager.VISIBILITY_NOT_VISIBLE);
2871         visibility.put("testpackage2", AccountManager.VISIBILITY_USER_MANAGED_NOT_VISIBLE);
2872         visibility.put("testpackage3", AccountManager.VISIBILITY_USER_MANAGED_VISIBLE);
2873 
2874         addAccountRemovedReceiver("testpackage1");
2875         mAms.registerAccountListener(
2876             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2877             "testpackage1"); // opPackageName
2878         mAms.registerAccountListener(
2879             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2880             "testpackage2"); // opPackageName
2881         mAms.registerAccountListener(
2882             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2883             "testpackage3"); // opPackageName
2884         mAms.addAccountExplicitlyWithVisibility(
2885             AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null, visibility);
2886 
2887         updateBroadcastCounters(2);
2888         assertEquals(mVisibleAccountsChangedBroadcasts, 1);
2889         assertEquals(mLoginAccountsChangedBroadcasts, 1);
2890 
2891         mAms.removeAccountInternal(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS);
2892 
2893         updateBroadcastCounters(4);
2894         assertEquals(mVisibleAccountsChangedBroadcasts, 2);
2895         assertEquals(mLoginAccountsChangedBroadcasts, 2);
2896         assertEquals(mAccountRemovedBroadcasts, 0); // account was never visible.
2897     }
2898 
2899     @SmallTest
testRegisterAccountListenerCredentialsUpdate()2900     public void testRegisterAccountListenerCredentialsUpdate() throws Exception {
2901         unlockSystemUser();
2902         mAms.registerAccountListener(
2903             new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2904             "testpackage"); // opPackageName
2905         mAms.addAccountExplicitly(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "p11", null);
2906         mAms.setPassword(AccountManagerServiceTestFixtures.ACCOUNT_SUCCESS, "pwd");
2907         updateBroadcastCounters(4);
2908         assertEquals(mVisibleAccountsChangedBroadcasts, 2);
2909         assertEquals(mLoginAccountsChangedBroadcasts, 2);
2910     }
2911 
2912     @SmallTest
testUnregisterAccountListenerNotRegistered()2913     public void testUnregisterAccountListenerNotRegistered() throws Exception {
2914         unlockSystemUser();
2915         try {
2916             mAms.unregisterAccountListener(
2917                 new String [] {AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1},
2918                 "testpackage"); // opPackageName
2919             fail("IllegalArgumentException expected. But no exception was thrown.");
2920         } catch (IllegalArgumentException e) {
2921             // IllegalArgumentException is expected.
2922         }
2923     }
2924 
updateBroadcastCounters(int expectedBroadcasts)2925     private void updateBroadcastCounters (int expectedBroadcasts){
2926         mVisibleAccountsChangedBroadcasts = 0;
2927         mLoginAccountsChangedBroadcasts = 0;
2928         mAccountRemovedBroadcasts = 0;
2929         ArgumentCaptor<Intent> captor = ArgumentCaptor.forClass(Intent.class);
2930         verify(mMockContext, atLeast(expectedBroadcasts)).sendBroadcastAsUser(captor.capture(),
2931             any(UserHandle.class));
2932         for (Intent intent : captor.getAllValues()) {
2933             if (AccountManager.ACTION_VISIBLE_ACCOUNTS_CHANGED.equals(intent.getAction())) {
2934                 mVisibleAccountsChangedBroadcasts++;
2935             } else if (AccountManager.LOGIN_ACCOUNTS_CHANGED_ACTION.equals(intent.getAction())) {
2936                 mLoginAccountsChangedBroadcasts++;
2937             } else if (AccountManager.ACTION_ACCOUNT_REMOVED.equals(intent.getAction())) {
2938                 mAccountRemovedBroadcasts++;
2939             }
2940         }
2941     }
2942 
addAccountRemovedReceiver(String packageName)2943     private void addAccountRemovedReceiver(String packageName) {
2944         ResolveInfo resolveInfo = new ResolveInfo();
2945         resolveInfo.activityInfo = new ActivityInfo();
2946         resolveInfo.activityInfo.applicationInfo =  new ApplicationInfo();
2947         resolveInfo.activityInfo.applicationInfo.packageName = packageName;
2948 
2949         List<ResolveInfo> accountRemovedReceivers = new ArrayList<>();
2950         accountRemovedReceivers.add(resolveInfo);
2951         when(mMockPackageManager.queryBroadcastReceiversAsUser(any(Intent.class), anyInt(),
2952             anyInt())).thenReturn(accountRemovedReceivers);
2953     }
2954 
2955     @SmallTest
testConcurrencyReadWrite()2956     public void testConcurrencyReadWrite() throws Exception {
2957         // Test 2 threads calling getAccounts and 1 thread setAuthToken
2958         unlockSystemUser();
2959         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
2960         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
2961 
2962         Account a1 = new Account("account1",
2963                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
2964         mAms.addAccountExplicitly(a1, "p1", null);
2965         List<String> errors = Collections.synchronizedList(new ArrayList<>());
2966         int readerCount = 2;
2967         ExecutorService es = Executors.newFixedThreadPool(readerCount + 1);
2968         AtomicLong readTotalTime = new AtomicLong(0);
2969         AtomicLong writeTotalTime = new AtomicLong(0);
2970         final CyclicBarrier cyclicBarrier = new CyclicBarrier(readerCount + 1);
2971 
2972         final int loopSize = 20;
2973         for (int t = 0; t < readerCount; t++) {
2974             es.submit(() -> {
2975                 for (int i = 0; i < loopSize; i++) {
2976                     String logPrefix = Thread.currentThread().getName() + " " + i;
2977                     waitForCyclicBarrier(cyclicBarrier);
2978                     cyclicBarrier.reset();
2979                     SystemClock.sleep(1); // Ensure that writer wins
2980                     Log.d(TAG, logPrefix + " getAccounts started");
2981                     long ti = System.currentTimeMillis();
2982                     try {
2983                         Account[] accounts = mAms.getAccounts(null, mContext.getOpPackageName());
2984                         if (accounts == null || accounts.length != 1
2985                                 || !AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1.equals(
2986                                 accounts[0].type)) {
2987                             String msg = logPrefix + ": Unexpected accounts: " + Arrays
2988                                     .toString(accounts);
2989                             Log.e(TAG, "    " + msg);
2990                             errors.add(msg);
2991                         }
2992                         Log.d(TAG, logPrefix + " getAccounts done");
2993                     } catch (Exception e) {
2994                         String msg = logPrefix + ": getAccounts failed " + e;
2995                         Log.e(TAG, msg, e);
2996                         errors.add(msg);
2997                     }
2998                     ti = System.currentTimeMillis() - ti;
2999                     readTotalTime.addAndGet(ti);
3000                 }
3001             });
3002         }
3003 
3004         es.submit(() -> {
3005             for (int i = 0; i < loopSize; i++) {
3006                 String logPrefix = Thread.currentThread().getName() + " " + i;
3007                 waitForCyclicBarrier(cyclicBarrier);
3008                 long ti = System.currentTimeMillis();
3009                 Log.d(TAG, logPrefix + " setAuthToken started");
3010                 try {
3011                     mAms.setAuthToken(a1, "t1", "v" + i);
3012                     Log.d(TAG, logPrefix + " setAuthToken done");
3013                 } catch (Exception e) {
3014                     errors.add(logPrefix + ": setAuthToken failed: " + e);
3015                 }
3016                 ti = System.currentTimeMillis() - ti;
3017                 writeTotalTime.addAndGet(ti);
3018             }
3019         });
3020         es.shutdown();
3021         assertTrue("Time-out waiting for jobs to finish",
3022                 es.awaitTermination(10, TimeUnit.SECONDS));
3023         es.shutdownNow();
3024         assertTrue("Errors: " + errors, errors.isEmpty());
3025         Log.i(TAG, "testConcurrencyReadWrite: readTotalTime=" + readTotalTime + " avg="
3026                 + (readTotalTime.doubleValue() / readerCount / loopSize));
3027         Log.i(TAG, "testConcurrencyReadWrite: writeTotalTime=" + writeTotalTime + " avg="
3028                 + (writeTotalTime.doubleValue() / loopSize));
3029     }
3030 
3031     @SmallTest
testConcurrencyRead()3032     public void testConcurrencyRead() throws Exception {
3033         // Test 2 threads calling getAccounts
3034         unlockSystemUser();
3035         String[] list = new String[]{AccountManagerServiceTestFixtures.CALLER_PACKAGE};
3036         when(mMockPackageManager.getPackagesForUid(anyInt())).thenReturn(list);
3037 
3038         Account a1 = new Account("account1",
3039                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
3040         mAms.addAccountExplicitly(a1, "p1", null);
3041         List<String> errors = Collections.synchronizedList(new ArrayList<>());
3042         int readerCount = 2;
3043         ExecutorService es = Executors.newFixedThreadPool(readerCount + 1);
3044         AtomicLong readTotalTime = new AtomicLong(0);
3045 
3046         final int loopSize = 20;
3047         for (int t = 0; t < readerCount; t++) {
3048             es.submit(() -> {
3049                 for (int i = 0; i < loopSize; i++) {
3050                     String logPrefix = Thread.currentThread().getName() + " " + i;
3051                     Log.d(TAG, logPrefix + " getAccounts started");
3052                     long ti = System.currentTimeMillis();
3053                     try {
3054                         Account[] accounts = mAms.getAccounts(null, mContext.getOpPackageName());
3055                         if (accounts == null || accounts.length != 1
3056                                 || !AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1.equals(
3057                                 accounts[0].type)) {
3058                             String msg = logPrefix + ": Unexpected accounts: " + Arrays
3059                                     .toString(accounts);
3060                             Log.e(TAG, "    " + msg);
3061                             errors.add(msg);
3062                         }
3063                         Log.d(TAG, logPrefix + " getAccounts done");
3064                     } catch (Exception e) {
3065                         String msg = logPrefix + ": getAccounts failed " + e;
3066                         Log.e(TAG, msg, e);
3067                         errors.add(msg);
3068                     }
3069                     ti = System.currentTimeMillis() - ti;
3070                     readTotalTime.addAndGet(ti);
3071                 }
3072             });
3073         }
3074         es.shutdown();
3075         assertTrue("Time-out waiting for jobs to finish",
3076                 es.awaitTermination(10, TimeUnit.SECONDS));
3077         es.shutdownNow();
3078         assertTrue("Errors: " + errors, errors.isEmpty());
3079         Log.i(TAG, "testConcurrencyRead: readTotalTime=" + readTotalTime + " avg="
3080                 + (readTotalTime.doubleValue() / readerCount / loopSize));
3081     }
3082 
waitForCyclicBarrier(CyclicBarrier cyclicBarrier)3083     private void waitForCyclicBarrier(CyclicBarrier cyclicBarrier) {
3084         try {
3085             cyclicBarrier.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
3086         } catch (Exception e) {
3087             throw new IllegalStateException("Should not throw " + e, e);
3088         }
3089     }
3090 
waitForLatch(CountDownLatch latch)3091     private void waitForLatch(CountDownLatch latch) {
3092         try {
3093             latch.await(LATCH_TIMEOUT_MS, TimeUnit.MILLISECONDS);
3094         } catch (InterruptedException e) {
3095             throw new IllegalStateException("Should not throw an InterruptedException", e);
3096         }
3097     }
3098 
createAddAccountOptions(String accountName)3099     private Bundle createAddAccountOptions(String accountName) {
3100         Bundle options = new Bundle();
3101         options.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName);
3102         return options;
3103     }
3104 
createGetAuthTokenOptions()3105     private Bundle createGetAuthTokenOptions() {
3106         Bundle options = new Bundle();
3107         options.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME,
3108                 AccountManagerServiceTestFixtures.CALLER_PACKAGE);
3109         options.putLong(AccountManagerServiceTestFixtures.KEY_TOKEN_EXPIRY,
3110                 System.currentTimeMillis() + ONE_DAY_IN_MILLISECOND);
3111         return options;
3112     }
3113 
encryptBundleWithCryptoHelper(Bundle sessionBundle)3114     private Bundle encryptBundleWithCryptoHelper(Bundle sessionBundle) {
3115         Bundle encryptedBundle = null;
3116         try {
3117             CryptoHelper cryptoHelper = CryptoHelper.getInstance();
3118             encryptedBundle = cryptoHelper.encryptBundle(sessionBundle);
3119         } catch (GeneralSecurityException e) {
3120             throw new IllegalStateException("Failed to encrypt session bundle.", e);
3121         }
3122         return encryptedBundle;
3123     }
3124 
createEncryptedSessionBundle(final String accountName)3125     private Bundle createEncryptedSessionBundle(final String accountName) {
3126         Bundle sessionBundle = new Bundle();
3127         sessionBundle.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName);
3128         sessionBundle.putString(
3129                 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1,
3130                 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1);
3131         sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE,
3132                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
3133         sessionBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.session.package");
3134         return encryptBundleWithCryptoHelper(sessionBundle);
3135     }
3136 
createEncryptedSessionBundleWithError(final String accountName)3137     private Bundle createEncryptedSessionBundleWithError(final String accountName) {
3138         Bundle sessionBundle = new Bundle();
3139         sessionBundle.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName);
3140         sessionBundle.putString(
3141                 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1,
3142                 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1);
3143         sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE,
3144                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
3145         sessionBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.session.package");
3146         sessionBundle.putInt(
3147                 AccountManager.KEY_ERROR_CODE, AccountManager.ERROR_CODE_INVALID_RESPONSE);
3148         sessionBundle.putString(AccountManager.KEY_ERROR_MESSAGE,
3149                 AccountManagerServiceTestFixtures.ERROR_MESSAGE);
3150         return encryptBundleWithCryptoHelper(sessionBundle);
3151     }
3152 
createEncryptedSessionBundleWithNoAccountType(final String accountName)3153     private Bundle createEncryptedSessionBundleWithNoAccountType(final String accountName) {
3154         Bundle sessionBundle = new Bundle();
3155         sessionBundle.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName);
3156         sessionBundle.putString(
3157                 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1,
3158                 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1);
3159         sessionBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.session.package");
3160         return encryptBundleWithCryptoHelper(sessionBundle);
3161     }
3162 
createAppBundle()3163     private Bundle createAppBundle() {
3164         Bundle appBundle = new Bundle();
3165         appBundle.putString(AccountManager.KEY_ANDROID_PACKAGE_NAME, "APCT.package");
3166         return appBundle;
3167     }
3168 
createOptionsWithAccountName(final String accountName)3169     private Bundle createOptionsWithAccountName(final String accountName) {
3170         Bundle sessionBundle = new Bundle();
3171         sessionBundle.putString(
3172                 AccountManagerServiceTestFixtures.SESSION_DATA_NAME_1,
3173                 AccountManagerServiceTestFixtures.SESSION_DATA_VALUE_1);
3174         sessionBundle.putString(AccountManager.KEY_ACCOUNT_TYPE,
3175                 AccountManagerServiceTestFixtures.ACCOUNT_TYPE_1);
3176         Bundle options = new Bundle();
3177         options.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_NAME, accountName);
3178         options.putBundle(AccountManagerServiceTestFixtures.KEY_ACCOUNT_SESSION_BUNDLE,
3179                 sessionBundle);
3180         options.putString(AccountManagerServiceTestFixtures.KEY_ACCOUNT_PASSWORD,
3181                 AccountManagerServiceTestFixtures.ACCOUNT_PASSWORD);
3182         return options;
3183     }
3184 
readNumberOfAccountsFromDbFile(Context context, String dbName)3185     private int readNumberOfAccountsFromDbFile(Context context, String dbName) {
3186         SQLiteDatabase ceDb = context.openOrCreateDatabase(dbName, 0, null);
3187         try (Cursor cursor = ceDb.rawQuery("SELECT count(*) FROM accounts", null)) {
3188             assertTrue(cursor.moveToNext());
3189             return cursor.getInt(0);
3190         }
3191     }
3192 
unlockSystemUser()3193     private void unlockSystemUser() {
3194         mAms.onUserUnlocked(newIntentForUser(UserHandle.USER_SYSTEM));
3195     }
3196 
newIntentForUser(int userId)3197     private static Intent newIntentForUser(int userId) {
3198         Intent intent = new Intent();
3199         intent.putExtra(Intent.EXTRA_USER_HANDLE, userId);
3200         return intent;
3201     }
3202 
3203     static class MyMockContext extends MockContext {
3204         private Context mTestContext;
3205         private Context mMockContext;
3206 
MyMockContext(Context testContext, Context mockContext)3207         MyMockContext(Context testContext, Context mockContext) {
3208             this.mTestContext = testContext;
3209             this.mMockContext = mockContext;
3210         }
3211 
3212         @Override
checkCallingOrSelfPermission(final String permission)3213         public int checkCallingOrSelfPermission(final String permission) {
3214             return mMockContext.checkCallingOrSelfPermission(permission);
3215         }
3216 
3217         @Override
bindServiceAsUser(Intent service, ServiceConnection conn, int flags, UserHandle user)3218         public boolean bindServiceAsUser(Intent service, ServiceConnection conn, int flags,
3219                 UserHandle user) {
3220             return mTestContext.bindServiceAsUser(service, conn, flags, user);
3221         }
3222 
3223         @Override
unbindService(ServiceConnection conn)3224         public void unbindService(ServiceConnection conn) {
3225             mTestContext.unbindService(conn);
3226         }
3227 
3228         @Override
getPackageManager()3229         public PackageManager getPackageManager() {
3230             return mMockContext.getPackageManager();
3231         }
3232 
3233         @Override
getPackageName()3234         public String getPackageName() {
3235             return mTestContext.getPackageName();
3236         }
3237 
3238         @Override
getSystemService(String name)3239         public Object getSystemService(String name) {
3240             return mMockContext.getSystemService(name);
3241         }
3242 
3243         @Override
getSystemServiceName(Class<?> serviceClass)3244         public String getSystemServiceName(Class<?> serviceClass) {
3245             return mMockContext.getSystemServiceName(serviceClass);
3246         }
3247 
3248         @Override
startActivityAsUser(Intent intent, UserHandle user)3249         public void startActivityAsUser(Intent intent, UserHandle user) {
3250             mMockContext.startActivityAsUser(intent, user);
3251         }
3252 
3253         @Override
registerReceiver(BroadcastReceiver receiver, IntentFilter filter)3254         public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
3255             return mMockContext.registerReceiver(receiver, filter);
3256         }
3257 
3258         @Override
registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user, IntentFilter filter, String broadcastPermission, Handler scheduler)3259         public Intent registerReceiverAsUser(BroadcastReceiver receiver, UserHandle user,
3260                 IntentFilter filter, String broadcastPermission, Handler scheduler) {
3261             return mMockContext.registerReceiverAsUser(
3262                     receiver, user, filter, broadcastPermission, scheduler);
3263         }
3264 
3265         @Override
openOrCreateDatabase(String file, int mode, SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler)3266         public SQLiteDatabase openOrCreateDatabase(String file, int mode,
3267                 SQLiteDatabase.CursorFactory factory, DatabaseErrorHandler errorHandler) {
3268             return mTestContext.openOrCreateDatabase(file, mode, factory,errorHandler);
3269         }
3270 
3271         @Override
getDatabasePath(String name)3272         public File getDatabasePath(String name) {
3273             return mTestContext.getDatabasePath(name);
3274         }
3275 
3276         @Override
sendBroadcastAsUser(Intent intent, UserHandle user)3277         public void sendBroadcastAsUser(Intent intent, UserHandle user) {
3278             mMockContext.sendBroadcastAsUser(intent, user);
3279         }
3280 
3281         @Override
getOpPackageName()3282         public String getOpPackageName() {
3283             return mMockContext.getOpPackageName();
3284         }
3285 
3286         @Override
createPackageContextAsUser(String packageName, int flags, UserHandle user)3287         public Context createPackageContextAsUser(String packageName, int flags, UserHandle user)
3288                 throws PackageManager.NameNotFoundException {
3289             return mMockContext.createPackageContextAsUser(packageName, flags, user);
3290         }
3291     }
3292 
3293     static class TestAccountAuthenticatorCache extends AccountAuthenticatorCache {
TestAccountAuthenticatorCache(Context realContext)3294         public TestAccountAuthenticatorCache(Context realContext) {
3295             super(realContext);
3296         }
3297 
3298         @Override
getUserSystemDirectory(int userId)3299         protected File getUserSystemDirectory(int userId) {
3300             return new File(mContext.getCacheDir(), "authenticator");
3301         }
3302     }
3303 
3304     static class TestInjector extends AccountManagerService.Injector {
3305         private Context mRealContext;
3306         private INotificationManager mMockNotificationManager;
TestInjector(Context realContext, Context mockContext, INotificationManager mockNotificationManager)3307         TestInjector(Context realContext,
3308                 Context mockContext,
3309                 INotificationManager mockNotificationManager) {
3310             super(mockContext);
3311             mRealContext = realContext;
3312             mMockNotificationManager = mockNotificationManager;
3313         }
3314 
3315         @Override
getMessageHandlerLooper()3316         Looper getMessageHandlerLooper() {
3317             return Looper.getMainLooper();
3318         }
3319 
3320         @Override
addLocalService(AccountManagerInternal service)3321         void addLocalService(AccountManagerInternal service) {
3322         }
3323 
3324         @Override
getAccountAuthenticatorCache()3325         IAccountAuthenticatorCache getAccountAuthenticatorCache() {
3326             return new TestAccountAuthenticatorCache(mRealContext);
3327         }
3328 
3329         @Override
getCeDatabaseName(int userId)3330         protected String getCeDatabaseName(int userId) {
3331             return new File(mRealContext.getCacheDir(), CE_DB).getPath();
3332         }
3333 
3334         @Override
getDeDatabaseName(int userId)3335         protected String getDeDatabaseName(int userId) {
3336             return new File(mRealContext.getCacheDir(), DE_DB).getPath();
3337         }
3338 
3339         @Override
getPreNDatabaseName(int userId)3340         String getPreNDatabaseName(int userId) {
3341             return new File(mRealContext.getCacheDir(), PREN_DB).getPath();
3342         }
3343 
3344         @Override
getNotificationManager()3345         INotificationManager getNotificationManager() {
3346             return mMockNotificationManager;
3347         }
3348     }
3349 
3350     class Response extends IAccountManagerResponse.Stub {
3351         private CountDownLatch mLatch;
3352         private IAccountManagerResponse mMockResponse;
Response(CountDownLatch latch, IAccountManagerResponse mockResponse)3353         public Response(CountDownLatch latch, IAccountManagerResponse mockResponse) {
3354             mLatch = latch;
3355             mMockResponse = mockResponse;
3356         }
3357 
3358         @Override
onResult(Bundle bundle)3359         public void onResult(Bundle bundle) {
3360             try {
3361                 mMockResponse.onResult(bundle);
3362             } catch (RemoteException e) {
3363             }
3364             mLatch.countDown();
3365         }
3366 
3367         @Override
onError(int code, String message)3368         public void onError(int code, String message) {
3369             try {
3370                 mMockResponse.onError(code, message);
3371             } catch (RemoteException e) {
3372             }
3373             mLatch.countDown();
3374         }
3375     }
3376 }
3377