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