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