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