1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
|
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.providers.contacts;
import com.google.android.collect.Sets;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.accounts.AuthenticatorException;
import android.accounts.OnAccountsUpdateListener;
import android.accounts.OperationCanceledException;
import android.content.ContentProvider;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.ProviderInfo;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.database.Cursor;
import android.location.Country;
import android.location.CountryDetector;
import android.location.CountryListener;
import android.net.Uri;
import android.os.Handler;
import android.os.Looper;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.provider.ContactsContract.AggregationExceptions;
import android.provider.ContactsContract.CommonDataKinds;
import android.provider.ContactsContract.CommonDataKinds.Email;
import android.provider.ContactsContract.CommonDataKinds.Phone;
import android.provider.ContactsContract.Contacts;
import android.provider.ContactsContract.Data;
import android.provider.ContactsContract.RawContacts;
import android.provider.ContactsContract.StatusUpdates;
import android.test.IsolatedContext;
import android.test.RenamingDelegatingContext;
import android.test.mock.MockContentResolver;
import android.test.mock.MockContext;
import android.test.mock.MockResources;
import android.util.TypedValue;
import java.io.IOException;
import java.util.Arrays;
import java.util.Locale;
import java.util.Set;
/**
* Helper class that encapsulates an "actor" which is owned by a specific
* package name. It correctly maintains a wrapped {@link Context} and an
* attached {@link MockContentResolver}. Multiple actors can be used to test
* security scenarios between multiple packages.
*/
public class ContactsActor {
private static final String FILENAME_PREFIX = "test.";
public static final String PACKAGE_GREY = "edu.example.grey";
public static final String PACKAGE_RED = "net.example.red";
public static final String PACKAGE_GREEN = "com.example.green";
public static final String PACKAGE_BLUE = "org.example.blue";
public Context context;
public String packageName;
public MockContentResolver resolver;
public ContentProvider provider;
private Country mMockCountry = new Country("us", 0);
private Account[] mAccounts = new Account[0];
private Set<String> mGrantedPermissions = Sets.newHashSet();
private CountryDetector mMockCountryDetector = new CountryDetector(null){
@Override
public Country detectCountry() {
return mMockCountry;
}
@Override
public void addCountryListener(CountryListener listener, Looper looper) {
}
};
private AccountManager mMockAccountManager;
private class MockAccountManager extends AccountManager {
public MockAccountManager(Context conteact) {
super(context, null, null);
}
@Override
public void addOnAccountsUpdatedListener(OnAccountsUpdateListener listener,
Handler handler, boolean updateImmediately) {
// do nothing
}
@Override
public Account[] getAccounts() {
return mAccounts;
}
@Override
public AccountManagerFuture<Account[]> getAccountsByTypeAndFeatures(
final String type, final String[] features,
AccountManagerCallback<Account[]> callback, Handler handler) {
return null;
}
@Override
public String blockingGetAuthToken(Account account, String authTokenType,
boolean notifyAuthFailure)
throws OperationCanceledException, IOException, AuthenticatorException {
return null;
}
}
private IsolatedContext mProviderContext;
/**
* Create an "actor" using the given parent {@link Context} and the specific
* package name. Internally, all {@link Context} method calls are passed to
* a new instance of {@link RestrictionMockContext}, which stubs out the
* security infrastructure.
*/
public ContactsActor(Context overallContext, String packageName,
Class<? extends ContentProvider> providerClass, String authority) throws Exception {
resolver = new MockContentResolver();
context = new RestrictionMockContext(overallContext, packageName, resolver,
mGrantedPermissions);
this.packageName = packageName;
RenamingDelegatingContext targetContextWrapper = new RenamingDelegatingContext(context,
overallContext, FILENAME_PREFIX);
mProviderContext = new IsolatedContext(resolver, targetContextWrapper){
@Override
public Object getSystemService(String name) {
if (Context.COUNTRY_DETECTOR.equals(name)) {
return mMockCountryDetector;
}
if (Context.ACCOUNT_SERVICE.equals(name)) {
return mMockAccountManager;
}
return super.getSystemService(name);
}
};
mMockAccountManager = new MockAccountManager(mProviderContext);
provider = addProvider(providerClass, authority);
}
public void addAuthority(String authority) {
resolver.addProvider(authority, provider);
}
public ContentProvider addProvider(Class<? extends ContentProvider> providerClass,
String authority) throws Exception {
ContentProvider provider = providerClass.newInstance();
ProviderInfo info = new ProviderInfo();
info.authority = authority;
provider.attachInfo(mProviderContext, info);
resolver.addProvider(authority, provider);
return provider;
}
public void addPermissions(String... permissions) {
mGrantedPermissions.addAll(Arrays.asList(permissions));
}
public void removePermissions(String... permissions) {
mGrantedPermissions.removeAll(Arrays.asList(permissions));
}
/**
* Mock {@link Context} that reports specific well-known values for testing
* data protection. The creator can override the owner package name, and
* force the {@link PackageManager} to always return a well-known package
* list for any call to {@link PackageManager#getPackagesForUid(int)}.
* <p>
* For example, the creator could request that the {@link Context} lives in
* package name "com.example.red", and also cause the {@link PackageManager}
* to report that no UID contains that package name.
*/
private static class RestrictionMockContext extends MockContext {
private final Context mOverallContext;
private final String mReportedPackageName;
private final ContactsMockPackageManager mPackageManager;
private final ContentResolver mResolver;
private final Resources mRes;
private final Set<String> mGrantedPermissions;
/**
* Create a {@link Context} under the given package name.
*/
public RestrictionMockContext(Context overallContext, String reportedPackageName,
ContentResolver resolver, Set<String> grantedPermissions) {
mOverallContext = overallContext;
mReportedPackageName = reportedPackageName;
mResolver = resolver;
mGrantedPermissions = grantedPermissions;
mPackageManager = new ContactsMockPackageManager();
mPackageManager.addPackage(1000, PACKAGE_GREY);
mPackageManager.addPackage(2000, PACKAGE_RED);
mPackageManager.addPackage(3000, PACKAGE_GREEN);
mPackageManager.addPackage(4000, PACKAGE_BLUE);
Resources resources = overallContext.getResources();
Configuration configuration = new Configuration(resources.getConfiguration());
configuration.locale = Locale.US;
resources.updateConfiguration(configuration, resources.getDisplayMetrics());
mRes = resources;
}
@Override
public String getPackageName() {
return mReportedPackageName;
}
@Override
public PackageManager getPackageManager() {
return mPackageManager;
}
@Override
public Resources getResources() {
return mRes;
}
@Override
public ContentResolver getContentResolver() {
return mResolver;
}
@Override
public ApplicationInfo getApplicationInfo() {
ApplicationInfo ai = new ApplicationInfo();
ai.packageName = "contactsTestPackage";
return ai;
}
// All permission checks are implemented to simply check against the granted permission set.
@Override
public int checkPermission(String permission, int pid, int uid) {
return checkCallingPermission(permission);
}
@Override
public int checkCallingPermission(String permission) {
if (mGrantedPermissions.contains(permission)) {
return PackageManager.PERMISSION_GRANTED;
} else {
return PackageManager.PERMISSION_DENIED;
}
}
@Override
public int checkCallingOrSelfPermission(String permission) {
return checkCallingPermission(permission);
}
@Override
public void enforcePermission(String permission, int pid, int uid, String message) {
enforceCallingPermission(permission, message);
}
@Override
public void enforceCallingPermission(String permission, String message) {
if (!mGrantedPermissions.contains(permission)) {
throw new SecurityException(message);
}
}
@Override
public void enforceCallingOrSelfPermission(String permission, String message) {
enforceCallingPermission(permission, message);
}
}
static String sCallingPackage = null;
void ensureCallingPackage() {
sCallingPackage = this.packageName;
}
public long createRawContact(String name) {
ensureCallingPackage();
long rawContactId = createRawContact();
createName(rawContactId, name);
return rawContactId;
}
public long createRawContact() {
ensureCallingPackage();
final ContentValues values = new ContentValues();
Uri rawContactUri = resolver.insert(RawContacts.CONTENT_URI, values);
return ContentUris.parseId(rawContactUri);
}
public long createRawContactWithStatus(String name, String address,
String status) {
final long rawContactId = createRawContact(name);
final long dataId = createEmail(rawContactId, address);
createStatus(dataId, status);
return rawContactId;
}
public long createName(long contactId, String name) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, contactId);
values.put(Data.IS_PRIMARY, 1);
values.put(Data.IS_SUPER_PRIMARY, 1);
values.put(Data.MIMETYPE, CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE);
values.put(CommonDataKinds.StructuredName.FAMILY_NAME, name);
Uri insertUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI,
contactId), RawContacts.Data.CONTENT_DIRECTORY);
Uri dataUri = resolver.insert(insertUri, values);
return ContentUris.parseId(dataUri);
}
public long createPhone(long contactId, String phoneNumber) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, contactId);
values.put(Data.IS_PRIMARY, 1);
values.put(Data.IS_SUPER_PRIMARY, 1);
values.put(Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE);
values.put(ContactsContract.CommonDataKinds.Phone.TYPE,
ContactsContract.CommonDataKinds.Phone.TYPE_HOME);
values.put(ContactsContract.CommonDataKinds.Phone.NUMBER, phoneNumber);
Uri insertUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI,
contactId), RawContacts.Data.CONTENT_DIRECTORY);
Uri dataUri = resolver.insert(insertUri, values);
return ContentUris.parseId(dataUri);
}
public long createEmail(long contactId, String address) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, contactId);
values.put(Data.IS_PRIMARY, 1);
values.put(Data.IS_SUPER_PRIMARY, 1);
values.put(Data.MIMETYPE, Email.CONTENT_ITEM_TYPE);
values.put(Email.TYPE, Email.TYPE_HOME);
values.put(Email.DATA, address);
Uri insertUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI,
contactId), RawContacts.Data.CONTENT_DIRECTORY);
Uri dataUri = resolver.insert(insertUri, values);
return ContentUris.parseId(dataUri);
}
public long createStatus(long dataId, String status) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(StatusUpdates.DATA_ID, dataId);
values.put(StatusUpdates.STATUS, status);
Uri dataUri = resolver.insert(StatusUpdates.CONTENT_URI, values);
return ContentUris.parseId(dataUri);
}
public void updateException(String packageProvider, String packageClient, boolean allowAccess) {
throw new UnsupportedOperationException("RestrictionExceptions are hard-coded");
}
public long getContactForRawContact(long rawContactId) {
ensureCallingPackage();
Uri contactUri = ContentUris.withAppendedId(RawContacts.CONTENT_URI, rawContactId);
final Cursor cursor = resolver.query(contactUri, Projections.PROJ_RAW_CONTACTS, null,
null, null);
if (!cursor.moveToFirst()) {
cursor.close();
throw new RuntimeException("Contact didn't have an aggregate");
}
final long aggId = cursor.getLong(Projections.COL_CONTACTS_ID);
cursor.close();
return aggId;
}
public int getDataCountForContact(long contactId) {
ensureCallingPackage();
Uri contactUri = Uri.withAppendedPath(ContentUris.withAppendedId(Contacts.CONTENT_URI,
contactId), Contacts.Data.CONTENT_DIRECTORY);
final Cursor cursor = resolver.query(contactUri, Projections.PROJ_ID, null, null,
null);
final int count = cursor.getCount();
cursor.close();
return count;
}
public int getDataCountForRawContact(long rawContactId) {
ensureCallingPackage();
Uri contactUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactId), Contacts.Data.CONTENT_DIRECTORY);
final Cursor cursor = resolver.query(contactUri, Projections.PROJ_ID, null, null,
null);
final int count = cursor.getCount();
cursor.close();
return count;
}
public void setSuperPrimaryPhone(long dataId) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(Data.IS_PRIMARY, 1);
values.put(Data.IS_SUPER_PRIMARY, 1);
Uri updateUri = ContentUris.withAppendedId(Data.CONTENT_URI, dataId);
resolver.update(updateUri, values, null, null);
}
public long createGroup(String groupName) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(ContactsContract.Groups.RES_PACKAGE, packageName);
values.put(ContactsContract.Groups.TITLE, groupName);
Uri groupUri = resolver.insert(ContactsContract.Groups.CONTENT_URI, values);
return ContentUris.parseId(groupUri);
}
public long createGroupMembership(long rawContactId, long groupId) {
ensureCallingPackage();
final ContentValues values = new ContentValues();
values.put(Data.RAW_CONTACT_ID, rawContactId);
values.put(Data.MIMETYPE, CommonDataKinds.GroupMembership.CONTENT_ITEM_TYPE);
values.put(CommonDataKinds.GroupMembership.GROUP_ROW_ID, groupId);
Uri insertUri = Uri.withAppendedPath(ContentUris.withAppendedId(RawContacts.CONTENT_URI,
rawContactId), RawContacts.Data.CONTENT_DIRECTORY);
Uri dataUri = resolver.insert(insertUri, values);
return ContentUris.parseId(dataUri);
}
protected void setAggregationException(int type, long rawContactId1, long rawContactId2) {
ContentValues values = new ContentValues();
values.put(AggregationExceptions.RAW_CONTACT_ID1, rawContactId1);
values.put(AggregationExceptions.RAW_CONTACT_ID2, rawContactId2);
values.put(AggregationExceptions.TYPE, type);
resolver.update(AggregationExceptions.CONTENT_URI, values, null, null);
}
public void setAccounts(Account[] accounts) {
mAccounts = accounts;
}
/**
* Various internal database projections.
*/
private interface Projections {
static final String[] PROJ_ID = new String[] {
BaseColumns._ID,
};
static final int COL_ID = 0;
static final String[] PROJ_RAW_CONTACTS = new String[] {
RawContacts.CONTACT_ID
};
static final int COL_CONTACTS_ID = 0;
}
}
|