Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Enforce item ownership permissions on content-provider

I have an exported content provider that is shared among several of my apps, and for which a third party could be free to write their own apps once I've published the API.

Right now any client app can execute any CRUD operation on any item in the content provider. I want to enforce some access permissions such that an app can only modify or delete items that it created, while still allowing any app to read all items in the provider and to create new items.

Is there any way I can access the UID of the calling app and store that with newly created items, and then compare against that value on future operations? Would it be better to use the package name? I assume the UID could change if the user uninstalled and reinstalled an app, and I don't want them to lose access to those items if they do so.

like image 947
TBridges42 Avatar asked Nov 09 '22 08:11

TBridges42


1 Answers

Yes you can do a package name check. Here's how you can retrieve the package name based on the calling uid :

private static Collection<String> getCallingPackages(Context context) {
    int callingUid = Binder.getCallingUid();
    if (callingUid == 0) {
        return Collections.emptyList();
    }

    String[] packages = context.getPackageManager().getPackagesForUid(callingUid);
    return new ArrayList<>(Arrays.asList(packages));
}

This returns a list of package names because, to quote the documentation :

In most cases, this will be a single package name, the package that has been assigned that user id.

Where there are multiple packages sharing the same user id through the "sharedUserId" mechanism, all packages with that id will be returned.

like image 90
XGouchet Avatar answered Nov 15 '22 13:11

XGouchet