Use context's userId in ContentResolver class.

- When registering and notifying observers, we should use the user in the
context as opposed to current user.
- Relax the permission check while registering and notifying content observers
to use INTERACT_ACROSS_USERS instead of INTERACT_ACROSS_USERS_FULL permission.

Change-Id: I973936903d4a2272c5722f3b98a057a40c0402be
Fixes: 32955100
Test: Created managed profile and verified that there are not failures.
      runtest -x core/tests/coretests/src/android/content/SecondaryUserContentResolverTest.java
      runtest -x core/tests/coretests/src/android/content/ManagedUserContentResolverTest.java
This commit is contained in:
Sudheer Shanka
2017-02-03 15:15:57 -08:00
parent 3b264fa2af
commit b4e2ddde4f
9 changed files with 385 additions and 12 deletions

View File

@@ -1886,7 +1886,7 @@ public abstract class ContentResolver {
ContentProvider.getUriWithoutUserId(uri),
notifyForDescendants,
observer,
ContentProvider.getUserIdFromUri(uri, UserHandle.myUserId()));
ContentProvider.getUserIdFromUri(uri, mContext.getUserId()));
}
/** @hide - designated user version */
@@ -1956,7 +1956,7 @@ public abstract class ContentResolver {
ContentProvider.getUriWithoutUserId(uri),
observer,
syncToNetwork,
ContentProvider.getUserIdFromUri(uri, UserHandle.myUserId()));
ContentProvider.getUserIdFromUri(uri, mContext.getUserId()));
}
/**
@@ -1982,7 +1982,7 @@ public abstract class ContentResolver {
ContentProvider.getUriWithoutUserId(uri),
observer,
flags,
ContentProvider.getUserIdFromUri(uri, UserHandle.myUserId()));
ContentProvider.getUserIdFromUri(uri, mContext.getUserId()));
}
/**

View File

@@ -1357,6 +1357,9 @@
</intent-filter>
</service>
<service android:name="android.content.CrossUserContentService"
android:exported="true" />
</application>
<instrumentation android:name="android.support.test.runner.AndroidJUnitRunner"

View File

@@ -29,6 +29,19 @@ import android.util.Log;
public class LocalProvider extends ContentProvider {
private static final String TAG = "LocalProvider";
private static final String AUTHORITY = "com.android.frameworks.coretests.LocalProvider";
private static final String TABLE_DATA_NAME = "data";
public static final Uri TABLE_DATA_URI =
Uri.parse("content://" + AUTHORITY + "/" + TABLE_DATA_NAME);
public static final String COLUMN_TEXT_NAME = "text";
public static final String COLUMN_INTEGER_NAME = "integer";
public static final String TEXT1 = "first data";
public static final String TEXT2 = "second data";
public static final int INTEGER1 = 100;
public static final int INTEGER2 = 101;
private SQLiteOpenHelper mOpenHelper;
private static final int DATA = 1;
@@ -51,13 +64,20 @@ public class LocalProvider extends ContentProvider {
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE data (" +
db.execSQL("CREATE TABLE " + TABLE_DATA_NAME + " (" +
"_id INTEGER PRIMARY KEY," +
"text TEXT, " +
"integer INTEGER);");
COLUMN_TEXT_NAME + " TEXT, " +
COLUMN_INTEGER_NAME + " INTEGER);");
// insert alarms
db.execSQL("INSERT INTO data (text, integer) VALUES ('first data', 100);");
db.execSQL(getInsertCommand(TEXT1, INTEGER1));
db.execSQL(getInsertCommand(TEXT2, INTEGER2));
}
private String getInsertCommand(String textValue, int integerValue) {
return "INSERT INTO " + TABLE_DATA_NAME
+ " (" + COLUMN_TEXT_NAME + ", " + COLUMN_INTEGER_NAME + ") "
+ "VALUES ('" + textValue + "', " + integerValue + ");";
}
@Override
@@ -74,6 +94,10 @@ public class LocalProvider extends ContentProvider {
public LocalProvider() {
}
static public Uri getTableDataUriForRow(int rowId) {
return Uri.parse("content://" + AUTHORITY + "/" + TABLE_DATA_NAME + "/" + rowId);
}
@Override
public boolean onCreate() {
mOpenHelper = new DatabaseHelper(getContext());

View File

@@ -0,0 +1,178 @@
/*
* Copyright (C) 2017 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 android.content;
import static org.junit.Assert.fail;
import android.app.ActivityManager;
import android.app.activity.LocalProvider;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.pm.UserInfo;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.UserManager;
import android.support.test.InstrumentationRegistry;
import android.support.test.filters.LargeTest;
import android.support.test.runner.AndroidJUnit4;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
@LargeTest
@RunWith(AndroidJUnit4.class)
abstract class AbstractCrossUserContentResolverTest {
private final static int TIMEOUT_SERVICE_CONNECTION_SEC = 4;
private final static int TIMEOUT_CONTENT_CHANGE_SEC = 4;
private Context mContext;
protected UserManager mUm;
private int mCrossUserId = -1;
private CrossUserContentServiceConnection mServiceConnection;
@Before
public void setUp() throws Exception {
mContext = InstrumentationRegistry.getContext();
mUm = UserManager.get(mContext);
final UserInfo userInfo = createUser();
mCrossUserId = userInfo.id;
final PackageManager pm = mContext.getPackageManager();
pm.installExistingPackageAsUser(mContext.getPackageName(), mCrossUserId);
ActivityManager.getService().startUserInBackground(mCrossUserId);
final CountDownLatch connectionLatch = new CountDownLatch(1);
mServiceConnection = new CrossUserContentServiceConnection(connectionLatch);
mContext.bindServiceAsUser(
new Intent(mContext, CrossUserContentService.class),
mServiceConnection,
Context.BIND_AUTO_CREATE,
UserHandle.of(mCrossUserId));
if (!connectionLatch.await(TIMEOUT_SERVICE_CONNECTION_SEC, TimeUnit.SECONDS)) {
fail("Timed out waiting for service connection to establish");
}
}
protected abstract UserInfo createUser() throws RemoteException ;
@After
public void tearDown() throws Exception {
if (mCrossUserId != -1) {
mUm.removeUser(mCrossUserId);
}
if (mServiceConnection != null) {
mContext.unbindService(mServiceConnection);
}
}
/**
* Register an observer for an URI in another user and verify that it receives
* onChange callback when data at the URI changes.
*/
@Test
public void testRegisterContentObserver() throws Exception {
Context crossUserContext = null;
String packageName = null;
try {
packageName = InstrumentationRegistry.getContext().getPackageName();
crossUserContext =
InstrumentationRegistry.getContext().createPackageContextAsUser(
packageName, 0 /* flags */, UserHandle.of(mCrossUserId));
} catch (NameNotFoundException e) {
fail("Couldn't find package " + packageName + " in u" + mCrossUserId);
}
final CountDownLatch updateLatch = new CountDownLatch(1);
final Uri uriToUpdate = LocalProvider.getTableDataUriForRow(2);
final TestContentObserver observer = new TestContentObserver(updateLatch,
uriToUpdate, mCrossUserId);
crossUserContext.getContentResolver().registerContentObserver(
LocalProvider.TABLE_DATA_URI, true, observer, mCrossUserId);
mServiceConnection.getService().updateContent(uriToUpdate, "New Text", 42);
if (!updateLatch.await(TIMEOUT_CONTENT_CHANGE_SEC, TimeUnit.SECONDS)) {
fail("Timed out waiting for the content change callback");
}
}
/**
* Register an observer for an URI in the current user and verify that another user can
* notify changes for this URI.
*/
@Test
public void testNotifyChange() throws Exception {
final CountDownLatch notifyLatch = new CountDownLatch(1);
final Uri notifyUri = LocalProvider.TABLE_DATA_URI;
final TestContentObserver observer = new TestContentObserver(notifyLatch,
notifyUri, UserHandle.myUserId());
mContext.getContentResolver().registerContentObserver(notifyUri, true, observer);
mServiceConnection.getService().notifyForUriAsUser(notifyUri, UserHandle.myUserId());
if (!notifyLatch.await(TIMEOUT_CONTENT_CHANGE_SEC, TimeUnit.SECONDS)) {
fail("Timed out waiting for the notify callback");
}
}
private static final class CrossUserContentServiceConnection implements ServiceConnection {
private ICrossUserContentService mService;
private final CountDownLatch mLatch;
public CrossUserContentServiceConnection(CountDownLatch latch) {
mLatch = latch;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mService = ICrossUserContentService.Stub.asInterface(service);
mLatch.countDown();
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
public ICrossUserContentService getService() {
return mService;
}
}
private static final class TestContentObserver extends ContentObserver {
private final CountDownLatch mLatch;
private final Uri mExpectedUri;
private final int mExpectedUserId;
public TestContentObserver(CountDownLatch latch, Uri exptectedUri, int expectedUserId) {
super(null);
mLatch = latch;
mExpectedUri = exptectedUri;
mExpectedUserId = expectedUserId;
}
@Override
public void onChange(boolean selfChange, Uri uri, int userId) {
if (mExpectedUri.equals(uri) && mExpectedUserId == userId) {
mLatch.countDown();
}
}
}
}

View File

@@ -0,0 +1,45 @@
/*
* Copyright (C) 2017 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 android.content;
import android.app.Service;
import android.app.activity.LocalProvider;
import android.net.Uri;
import android.os.IBinder;
public class CrossUserContentService extends Service {
@Override
public IBinder onBind(Intent intent) {
return mLocalService.asBinder();
}
private ICrossUserContentService mLocalService = new ICrossUserContentService.Stub() {
@Override
public void updateContent(Uri uri, String key, int value) {
final ContentValues values = new ContentValues();
values.put(LocalProvider.COLUMN_TEXT_NAME, key);
values.put(LocalProvider.COLUMN_INTEGER_NAME, value);
getContentResolver().update(uri, values, null, null);
}
@Override
public void notifyForUriAsUser(Uri uri, int userId) {
getContentResolver().notifyChange(uri, null, false, userId);
}
};
}

View File

@@ -0,0 +1,24 @@
/*
* Copyright (C) 2017 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 android.content;
import android.net.Uri;
interface ICrossUserContentService {
void updateContent(in Uri uri, String key, int value);
void notifyForUriAsUser(in Uri uri, int userId);
}

View File

@@ -0,0 +1,42 @@
/*
* Copyright (C) 2017 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 android.content;
import android.content.pm.UserInfo;
import android.os.RemoteException;
import android.os.UserHandle;
/**
* To run the tests, use
*
* runtest -c android.content.ManagedUserContentResolverTest frameworks-core
*
* or the following steps:
*
* Build: m FrameworksCoreTests
* Install: adb install -r \
* ${ANDROID_PRODUCT_OUT}/data/app/FrameworksCoreTests/FrameworksCoreTests.apk
* Run: adb shell am instrument -e class android.content.ManagedUserContentResolverTest -w \
* com.android.frameworks.coretests/android.support.test.runner.AndroidJUnitRunner
*/
public class ManagedUserContentResolverTest extends AbstractCrossUserContentResolverTest {
@Override
protected UserInfo createUser() throws RemoteException {
return mUm.createProfileForUser("Managed user",
UserInfo.FLAG_MANAGED_PROFILE, UserHandle.myUserId());
}
}

View File

@@ -0,0 +1,40 @@
/*
* Copyright (C) 2017 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 android.content;
import android.content.pm.UserInfo;
import android.os.RemoteException;
/**
* To run the tests, use
*
* runtest -c android.content.SecondaryUserContentResolverTest frameworks-core
*
* or the following steps:
*
* Build: m FrameworksCoreTests
* Install: adb install -r \
* ${ANDROID_PRODUCT_OUT}/data/app/FrameworksCoreTests/FrameworksCoreTests.apk
* Run: adb shell am instrument -e class android.content.SecondaryUserContentResolverTest -w \
* com.android.frameworks.coretests/android.support.test.runner.AndroidJUnitRunner
*/
public class SecondaryUserContentResolverTest extends AbstractCrossUserContentResolverTest {
@Override
protected UserInfo createUser() throws RemoteException {
return mUm.createUser("Secondary user", 0);
}
}

View File

@@ -296,7 +296,7 @@ public final class ContentService extends IContentService.Stub {
final int pid = Binder.getCallingPid();
userHandle = handleIncomingUser(uri, pid, uid,
Intent.FLAG_GRANT_READ_URI_PERMISSION, userHandle);
Intent.FLAG_GRANT_READ_URI_PERMISSION, true, userHandle);
final String msg = LocalServices.getService(ActivityManagerInternal.class)
.checkContentProviderAccess(uri.getAuthority(), userHandle);
@@ -354,7 +354,7 @@ public final class ContentService extends IContentService.Stub {
final int callingUserHandle = UserHandle.getCallingUserId();
userHandle = handleIncomingUser(uri, pid, uid,
Intent.FLAG_GRANT_WRITE_URI_PERMISSION, userHandle);
Intent.FLAG_GRANT_WRITE_URI_PERMISSION, true, userHandle);
final String msg = LocalServices.getService(ActivityManagerInternal.class)
.checkContentProviderAccess(uri.getAuthority(), userHandle);
@@ -1125,7 +1125,8 @@ public final class ContentService extends IContentService.Stub {
}
}
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, int userId) {
private int handleIncomingUser(Uri uri, int pid, int uid, int modeFlags, boolean allowNonFull,
int userId) {
if (userId == UserHandle.USER_CURRENT) {
userId = ActivityManager.getCurrentUser();
}
@@ -1138,8 +1139,24 @@ public final class ContentService extends IContentService.Stub {
} else if (userId != UserHandle.getCallingUserId()) {
if (checkUriPermission(uri, pid, uid, modeFlags,
userId) != PackageManager.PERMISSION_GRANTED) {
mContext.enforceCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL, TAG);
boolean allow = false;
if (mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS_FULL)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
} else if (allowNonFull && mContext.checkCallingOrSelfPermission(
Manifest.permission.INTERACT_ACROSS_USERS)
== PackageManager.PERMISSION_GRANTED) {
allow = true;
}
if (!allow) {
final String permissions = allowNonFull
? (Manifest.permission.INTERACT_ACROSS_USERS_FULL + " or " +
Manifest.permission.INTERACT_ACROSS_USERS)
: Manifest.permission.INTERACT_ACROSS_USERS_FULL;
throw new SecurityException(TAG + "Neither user " + uid
+ " nor current process has " + permissions);
}
}
}