update OpenHarmony 2.0 Canary

This commit is contained in:
mamingshuai 2021-06-02 00:43:21 +08:00
parent 9be5fe2691
commit 17a9284960
94 changed files with 6470 additions and 142 deletions

15
.gitattributes vendored Normal file
View File

@ -0,0 +1,15 @@
*.tgz filter=lfs diff=lfs merge=lfs -text
*.trp filter=lfs diff=lfs merge=lfs -text
*.apk filter=lfs diff=lfs merge=lfs -text
*.jar filter=lfs diff=lfs merge=lfs -text
*.mp4 filter=lfs diff=lfs merge=lfs -text
*.zip filter=lfs diff=lfs merge=lfs -text
*.asm filter=lfs diff=lfs merge=lfs -text
*.8svn filter=lfs diff=lfs merge=lfs -text
*.9svn filter=lfs diff=lfs merge=lfs -text
*.dylib filter=lfs diff=lfs merge=lfs -text
*.exe filter=lfs diff=lfs merge=lfs -text
*.a filter=lfs diff=lfs merge=lfs -text
*.so filter=lfs diff=lfs merge=lfs -text
*.bin filter=lfs diff=lfs merge=lfs -text
*.dll filter=lfs diff=lfs merge=lfs -text

34
BUILD.gn Executable file
View File

@ -0,0 +1,34 @@
# Copyright (C) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos.gni")
group("permission_build_module_standard") {
if (is_standard_system) {
deps = [
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard",
"//base/security/permission/services/permission_standard/permissionmanagerservice:permission_manager_service_standard",
"//base/security/permission/services/permission_standard/permissionmanagerservice/main/sa_profile:permission_sa_profile_standard",
]
}
}
group("permission_build_module_standard_test") {
testonly = true
deps = []
if (is_standard_system) {
deps += [
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/test:unittest",
"//base/security/permission/services/permission_standard/permissionmanagerservice/test:unittest",
]
}
}

0
LICENSE Normal file → Executable file
View File

64
OAT.xml Executable file
View File

@ -0,0 +1,64 @@
<?xml version="1.0" encoding="UTF-8"?>
<!-- Copyright (c) 2021 Huawei Device Co., Ltd.
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.
Notes:
This is project config file for OpenHarmony OSS Audit Tool, if you have any questions or concerns, please email chenyaxun.
-->
<!-- OAT(OSS Audit Tool) configuration guide:
basedir: Root dir, the basedir + project path is the real source file location.
licensefile:
1.If the project don't have "LICENSE" in root dir, please define all the license files in this project in , OAT will check license files according to this rule.
tasklist(only for batch mode):
1. task: Define oat check thread, each task will start a new thread.
2. task name: Only an name, no practical effect.
3. task policy: Default policy for projects under this task, this field is required and the specified policy must defined in policylist.
4. task filter: Default filefilter for projects under this task, this field is required and the specified filefilter must defined in filefilterlist.
5. task project: Projects to be checked, the path field define the source root dir of the project.
policyList:
1. policy: All policyitems will be merged to default OAT.xml rules, the name of policy doesn't affect OAT check process.
2. policyitem: The fields type, name, path, desc is required, and the fields rule, group, filefilter is optional,the default value is:
<policyitem type="" name="" path="" desc="" rule="may" group="defaultGroup" filefilter="defaultPolicyFilter"/>
3. policyitem type:
"compatibility" is used to check license compatibility in the specified path;
"license" is used to check source license header in the specified path;
"copyright" is used to check source copyright header in the specified path;
"import" is used to check source dependency in the specified path, such as import ... ,include ...
"filetype" is used to check file type in the specified path, supported file types: archive, binary
"filename" is used to check whether the specified file exists in the specified path(support projectroot in default OAT.xml), supported file names: LICENSE, README, README.OpenSource
4. policyitem name: This field is used for define the license, copyright, "*" means match all, the "!" prefix means could not match this value. For example, "!GPL" means can not use GPL license.
5. policyitem path: This field is used for define the source file scope to apply this policyitem, the "!" prefix means exclude the files. For example, "!.*/lib/.*" means files in lib dir will be exclude while process this policyitem.
6. policyitem rule and group: These two fields are used together to merge policy results. "may" policyitems in the same group means any one in this group passed, the result will be passed.
7. policyitem filefilter: Used to bind filefilter which define filter rules.
8. filefilter: Filter rules, the type filename is used to filter file name, the type filepath is used to filter file path.
Note:If the text contains special characters, please escape them according to the following rules:
" == &gt;
& == &gt;
' == &gt;
< == &gt;
> == &gt;
-->
<configuration>
<oatconfig>
<filefilterlist>
<filefilter name="licenseFileNamePolicyFilter" desc="Filters for LICENSE file policies" >
</filefilter>
</filefilterlist>
</oatconfig>
</configuration>

407
README.md
View File

@ -1,104 +1,369 @@
# permission\_lite<a name="EN-US_TOPIC_0000001123217533"></a>
# security\_permission<a name="EN-US_TOPIC_0000001101239136"></a>
- [Application Permission Management](#section20822104317111)
- [IPC Authentication](#section156859591110)
- [Introduction](#section11660541593)
- [Directory Structure](#section161941989596)
- [Constraints](#section119744591305)
- [Usage](#section137768191623)
- [Available APIs](#section1551164914237)
- [Usage Guidelines](#section129654513264)
## Application Permission Management<a name="section20822104317111"></a>
- [Repositories Involved](#section1371113476307)
Application permissions are used to control access to system resources and features related to personal privacy, for example, accessing hardware features of personal devices such as cameras and microphones, and reading and writing media files. The OS protects such data and features through application permission management.
## Introduction<a name="section11660541593"></a>
The following table describes fields in a permission.
In OpenHarmony, apps and system services run in independent sandboxes. Both processes and data are isolated from each other to protect the security of app data. However, services or apps running in the sandboxes provide some APIs to implement specific functionalities. To access these APIs across processes, apps in other sandboxes need the required permissions, which are granted and managed based on a permission management mechanism.
<a name="table1073153511418"></a>
<table><thead align="left"><tr id="row11107193541417"><th class="cellrowborder" valign="top" width="22.220000000000002%" id="mcps1.1.4.1.1"><p id="p6107535141420"><a name="p6107535141420"></a><a name="p6107535141420"></a>Field</p>
- App permission management provides a mechanism for defining permissions, allowing system services and apps to define new permissions for their sensitive APIs. To access these APIs, other apps need the required permissions.
- App permission management also allows apps to request permissions that are defined by the system or other apps. Upon obtaining the permissions, apps can access the sensitive APIs provided by the system or other apps.
- In addition, app permission management allows users to view and manage the permission granting status.
**Figure 1** App permission management architecture<a name="fig4460722185514"></a>
![](figures/en-us_image_0000001113598272.png)
App permission management provides permission management for the application framework subsystem and provides APIs for apps to request permissions and query the permission granting status. Currently, app permission management is available for large and standard systems.
- Mini system: refers to the system running on the devices whose memory is greater than or equal to 128 KB and that are equipped with MCU processors such as ARM Cortex-M and 32-bit RISC-V. This system provides multiple lightweight network protocols and graphics frameworks, and a wide range of read/write components for the IoT bus. Typical products include connection modules, sensors, and wearables for smart home.
- Small system: refers to the system running on the devices whose memory is greater than or equal to 1 MB and that are equipped with app processors such as ARM Cortex-A. This system provides higher security capabilities, standard graphics frameworks, and video encoding and decoding capabilities. Typical products include smart home IP cameras, electronic cat eyes, and routers, and event data recorders \(EDRs\) for smart travel.
- Standard system: refers to the system running on the devices whose memory is greater than or equal to 128 MB and that are equipped with app processors such as ARM Cortex-A. This system provides a complete application framework supporting the enhanced interaction, 3D GPU, hardware composer, diverse components, and rich animations. This system applies to high-end refrigerator displays.
## Directory Structure<a name="section161941989596"></a>
```
/base/security/permission
├── frameworks # Frameworks
│ └── permission_standard # Permission management framework for the standard system
├── interfaces # APIs
│ ├── innerkits # Internal APIs
│ │ ├── permission_lite # Internal permission management APIs for the mini and small systems
│ │ └── permission_standard # Internal permission management APIs for the standard system
│ └── kits # External APIs
│ ├── permission_lite # External permission management APIs for the mini and small systems
│ └── permission_standard # External permission management APIs for the standard system
└── services # Services
├── permission_lite # Permission management services for the mini and small systems
└── permission_standard # Permission management services for the standard system
```
## Constraints<a name="section119744591305"></a>
- Currently, C++ APIs are available only for local permission management in the standard system. Distributed permission management APIs are not provided yet.
## Usage<a name="section137768191623"></a>
### Available APIs<a name="section1551164914237"></a>
**App permission management for a standard system**: provides basic permission management and verification capabilities for the application framework subsystem of a standard system and is unavailable for third-party apps. The following table describes the available APIs.
<a name="table17351104911243"></a>
<table><thead align="left"><tr id="row43512497244"><th class="cellrowborder" valign="top" width="73.41%" id="mcps1.1.3.1.1"><p id="p8351104918247"><a name="p8351104918247"></a><a name="p8351104918247"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="35.099999999999994%" id="mcps1.1.4.1.2"><p id="p111080352143"><a name="p111080352143"></a><a name="p111080352143"></a>Value</p>
</th>
<th class="cellrowborder" valign="top" width="42.68%" id="mcps1.1.4.1.3"><p id="p161080358141"><a name="p161080358141"></a><a name="p161080358141"></a>Description</p>
<th class="cellrowborder" valign="top" width="26.590000000000003%" id="mcps1.1.3.1.2"><p id="p7351174913247"><a name="p7351174913247"></a><a name="p7351174913247"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row151081735111418"><td class="cellrowborder" valign="top" width="22.220000000000002%" headers="mcps1.1.4.1.1 "><p id="p1108193521417"><a name="p1108193521417"></a><a name="p1108193521417"></a>name</p>
<tbody><tr id="row143511494244"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p2504174918322"><a name="p2504174918322"></a><a name="p2504174918322"></a>int VerifyPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="35.099999999999994%" headers="mcps1.1.4.1.2 "><p id="p131081435151413"><a name="p131081435151413"></a><a name="p131081435151413"></a>String</p>
</td>
<td class="cellrowborder" valign="top" width="42.68%" headers="mcps1.1.4.1.3 "><p id="p0108235141411"><a name="p0108235141411"></a><a name="p0108235141411"></a>Permission name</p>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p14504549163217"><a name="p14504549163217"></a><a name="p14504549163217"></a>Checks whether a specified app has been granted the given permission.</p>
</td>
</tr>
<tr id="row19108143516148"><td class="cellrowborder" valign="top" width="22.220000000000002%" headers="mcps1.1.4.1.1 "><p id="p51081355145"><a name="p51081355145"></a><a name="p51081355145"></a>reason</p>
<tr id="row217303717326"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p8504849123210"><a name="p8504849123210"></a><a name="p8504849123210"></a>bool CanRequestPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="35.099999999999994%" headers="mcps1.1.4.1.2 "><p id="p01082358147"><a name="p01082358147"></a><a name="p01082358147"></a>Multi-language string ID</p>
</td>
<td class="cellrowborder" valign="top" width="42.68%" headers="mcps1.1.4.1.3 "><p id="p191081235171414"><a name="p191081235171414"></a><a name="p191081235171414"></a>Purpose of requesting the permission</p>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p850417499329"><a name="p850417499329"></a><a name="p850417499329"></a>Checks whether a specified app can request the given permission through a pop-up window.</p>
</td>
</tr>
<tr id="row13108123516145"><td class="cellrowborder" valign="top" width="22.220000000000002%" headers="mcps1.1.4.1.1 "><p id="p18109835101415"><a name="p18109835101415"></a><a name="p18109835101415"></a>used-scene{</p>
<p id="p910913358146"><a name="p910913358146"></a><a name="p910913358146"></a>ability,</p>
<p id="p11109235181420"><a name="p11109235181420"></a><a name="p11109235181420"></a>when</p>
<p id="p16109193531417"><a name="p16109193531417"></a><a name="p16109193531417"></a>}</p>
<tr id="row677573713220"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p16504124933210"><a name="p16504124933210"></a><a name="p16504124933210"></a>int GrantUserGrantedPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="35.099999999999994%" headers="mcps1.1.4.1.2 "><p id="p4109123511420"><a name="p4109123511420"></a><a name="p4109123511420"></a><strong id="b2227185715217"><a name="b2227185715217"></a><a name="b2227185715217"></a>ability</strong>: string of the component class name</p>
<p id="p19109133531410"><a name="p19109133531410"></a><a name="p19109133531410"></a>when:inuse, always</p>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p115042494327"><a name="p115042494327"></a><a name="p115042494327"></a>Grants a specified user_grant permission to the given app.</p>
</td>
<td class="cellrowborder" valign="top" width="42.68%" headers="mcps1.1.4.1.3 "><p id="p31091835151413"><a name="p31091835151413"></a><a name="p31091835151413"></a>Scene where the APIs controlled by this permission are called.</p>
<p id="p93361156407"><a name="p93361156407"></a><a name="p93361156407"></a>This field declares what components can call the APIs controlled by this permission in the specified scene (foreground/background).</p>
</tr>
<tr id="row722533813329"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p9504114963210"><a name="p9504114963210"></a><a name="p9504114963210"></a>int GrantSystemGrantedPermission(const string&amp; bundleName, const string&amp; permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p850412493329"><a name="p850412493329"></a><a name="p850412493329"></a>Grants a specified system_grant permission to the given app.</p>
</td>
</tr>
<tr id="row1354353873216"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p450414919328"><a name="p450414919328"></a><a name="p450414919328"></a>int RevokeUserGrantedPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p1050411498327"><a name="p1050411498327"></a><a name="p1050411498327"></a>Revokes a specified user_grant permission from the given app.</p>
</td>
</tr>
<tr id="row1073519380323"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p1850484933212"><a name="p1850484933212"></a><a name="p1850484933212"></a>int RevokeSystemGrantedPermission(const string&amp; bundleName, const string&amp; permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p35048492326"><a name="p35048492326"></a><a name="p35048492326"></a>Revokes a specified system_grant permission from the given app.</p>
</td>
</tr>
<tr id="row1692163820325"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p9504134953215"><a name="p9504134953215"></a><a name="p9504134953215"></a>int AddUserGrantedReqPermissions(const string&amp; bundleName, const std::vector&lt;string&gt;&amp; permList, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p250424993212"><a name="p250424993212"></a><a name="p250424993212"></a>Adds user_grant permissions requested by a specified app.</p>
</td>
</tr>
<tr id="row1890399325"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p1950413498329"><a name="p1950413498329"></a><a name="p1950413498329"></a>int AddSystemGrantedReqPermissions(const string&amp; bundleName, const std::vector&lt;string&gt;&amp; permList)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p1150444943210"><a name="p1150444943210"></a><a name="p1150444943210"></a>Adds system_grant permissions requested by a specified app.</p>
</td>
</tr>
<tr id="row13257153973215"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p2505184917329"><a name="p2505184917329"></a><a name="p2505184917329"></a>int RemoveUserGrantedReqPermissions(const string&amp; bundleName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p950514973212"><a name="p950514973212"></a><a name="p950514973212"></a>Removes all the user_grant permissions requested by a specified app.</p>
</td>
</tr>
<tr id="row144437398322"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p205051049103214"><a name="p205051049103214"></a><a name="p205051049103214"></a>int RemoveSystemGrantedReqPermissions(const string&amp; bundleName)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p125051349123213"><a name="p125051349123213"></a><a name="p125051349123213"></a>Removes all the system_grant permissions requested by a specified app.</p>
</td>
</tr>
<tr id="row13617183915329"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p16505049173217"><a name="p16505049173217"></a><a name="p16505049173217"></a>int AddDefPermissions(const std::vector&lt;PermissionDef&gt;&amp; permList)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p13505849103215"><a name="p13505849103215"></a><a name="p13505849103215"></a>Adds the permissions defined by the app.</p>
</td>
</tr>
<tr id="row117857394324"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p105059492325"><a name="p105059492325"></a><a name="p105059492325"></a>int GetDefPermission(const string&amp; permissionName, PermissionDef&amp; permissionDefResult)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p11505349103220"><a name="p11505349103220"></a><a name="p11505349103220"></a>Obtains the definition of the permission with a specified name.</p>
</td>
</tr>
</tbody>
</table>
## IPC Authentication<a name="section156859591110"></a>
**App permission management for a mini or small system**: The following table lists the available APIs, which can be called only by system apps and services.
- If system services registered with Samgr provide APIs for other processes to access the services through IPC, access control policies must be configured; otherwise, access to the system services will be denied.
- You can configure access control policies in **base/security/permission/services/permission\_lite/ipc\_auth/include/policy\_preset.h**.
<a name="table9789027162518"></a>
<table><thead align="left"><tr id="row9789427112518"><th class="cellrowborder" valign="top" width="55.66%" id="mcps1.1.3.1.1"><p id="p9790102717251"><a name="p9790102717251"></a><a name="p9790102717251"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="44.34%" id="mcps1.1.3.1.2"><p id="p779032715251"><a name="p779032715251"></a><a name="p779032715251"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row187901627112516"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p138014275353"><a name="p138014275353"></a><a name="p138014275353"></a>int CheckPermission(int uid, const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p57901727202510"><a name="p57901727202510"></a><a name="p57901727202510"></a>Checks whether the app with a specified UID has the permission to access system service APIs.</p>
</td>
</tr>
<tr id="row19341734164410"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p123453412448"><a name="p123453412448"></a><a name="p123453412448"></a>int CheckSelfPermission(const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p937645212447"><a name="p937645212447"></a><a name="p937645212447"></a>Checks whether the caller has the permission to access system service APIs.</p>
</td>
</tr>
<tr id="row879032715258"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p13071135133514"><a name="p13071135133514"></a><a name="p13071135133514"></a>int QueryPermission(const char *identifier, PermissionSaved **permissions, int *permNum)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p1379072718259"><a name="p1379072718259"></a><a name="p1379072718259"></a>Queries all permissions requested by the app and checks whether the requested permissions have been granted.</p>
</td>
</tr>
<tr id="row877239193516"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p878133903516"><a name="p878133903516"></a><a name="p878133903516"></a>int GrantPermission(const char *identifier, const char *permName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p678143943515"><a name="p678143943515"></a><a name="p678143943515"></a>Grants a specified permission to the app.</p>
</td>
</tr>
<tr id="row3616164223510"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p1617142163517"><a name="p1617142163517"></a><a name="p1617142163517"></a>int RevokePermission(const char *identifier, const char *permName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p06171242143517"><a name="p06171242143517"></a><a name="p06171242143517"></a>Revokes a specified permission from the app.</p>
</td>
</tr>
<tr id="row13790122742516"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p23273123365"><a name="p23273123365"></a><a name="p23273123365"></a>int GrantRuntimePermission(int uid, const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p177908273259"><a name="p177908273259"></a><a name="p177908273259"></a>Grants a specified runtime permission to the app.</p>
</td>
</tr>
<tr id="row18566191217452"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p169891916194512"><a name="p169891916194512"></a><a name="p169891916194512"></a>int RevokeRuntimePermission(int uid, const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p937132011440"><a name="p937132011440"></a><a name="p937132011440"></a>Revokes a specified runtime permission from the app.</p>
</td>
</tr>
</tbody>
</table>
1. Define the policies for each feature.
**IPC authentication for a mini or small system**
2. Add the feature policies to the global policy.
<a name="table10494122145517"></a>
<table><thead align="left"><tr id="row1494152195511"><th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.1"><p id="p14941221135515"><a name="p14941221135515"></a><a name="p14941221135515"></a>API</p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.2"><p id="p8494172116555"><a name="p8494172116555"></a><a name="p8494172116555"></a>Description</p>
</th>
</tr>
</thead>
<tbody><tr id="row1849482118555"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p1414381815720"><a name="p1414381815720"></a><a name="p1414381815720"></a>int GetCommunicationStrategy(RegParams params, PolicyTrans **policies, unsigned int *policyNum)</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p749582195510"><a name="p749582195510"></a><a name="p749582195510"></a>Obtains the access policies of a service API.</p>
</td>
</tr>
<tr id="row8495521115517"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p966319247576"><a name="p966319247576"></a><a name="p966319247576"></a>int IsCommunicationAllowed(AuthParams params)</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p134951921115511"><a name="p134951921115511"></a><a name="p134951921115511"></a>Checks whether a process has the permission to access an API of another process.</p>
</td>
</tr>
</tbody>
</table>
### Usage Guidelines<a name="section129654513264"></a>
**App permission management for a standard system**
The APIs provided are for internal use and unavailable to developers. During the authentication, you only need to call **VerifyPermission**.
1. Determine the app UID and the name of the permission to verify.
2. Obtain the app bundle name based on the app UID.
3. Obtain the user ID of the app based on the UID.
4. Pass the permission name, bundle name, and user ID to **VerifyPermission\(string permissionName, string bundleName, int userId\)**.
5. Obtain the verification result.
**App permission management for a mini or small system**
This section uses the bundle manager as an example to describe the app permission development. Before starting development, you need to declare the required sensitive permissions in the **config.json** file. During app installation, the BMS calls APIs of the app permission management component to check whether the required permissions have been granted. If yes, the installation proceeds; if not, the installation fails.
1. Declare the required permission \(**ohos.permission.INSTALL\_BUNDLE**\) in the **config.json** file.
```
{
...
"module": {
"package": "ohos.demo.kitframework",
"deviceType": [
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartCamera", "smartVision"
],
"reqPermissions": [{
// Declare the ohos.permission.INSTALL_BUNDLE permission required for installing the app.
"name": "ohos.permission.INSTALL_BUNDLE",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
},
{
"name": "ohos.permission.LISTEN_BUNDLE_CHANGE",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
},
{
"name": "ohos.permission.GET_BUNDLE_INFO",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
}
],
...
}
```
2. The BMS calls the corresponding API of the app permission management component \(for example, the **CheckPermission** function with **ohos.permission.INSTALL\_BUNDLE** as an input parameter\) to check whether the BMS has the permission to install the app. If yes, the installation proceeds; if not, the installation fails.
```
constexpr static char PERMISSION_INSTALL_BUNDLE[] = "ohos.permission.INSTALL_BUNDLE";
bool Install(const char *hapPath, const InstallParam *installParam, InstallerCallback installerCallback)
{
if ((hapPath == nullptr) || (installerCallback == nullptr) || (installParam == nullptr)) {
HILOG_ERROR(HILOG_MODULE_APP, "BundleManager install failed due to nullptr parameters");
return false;
}
// Check whether the ohos.permission.INSTALL_BUNDLE permission has been granted.
if (CheckPermission(0, static_cast<const char *>(PERMISSION_INSTALL_BUNDLE)) != GRANTED) {
HILOG_ERROR(HILOG_MODULE_APP, "BundleManager install failed due to permission denied");
return false; // App installation fails.
}
// App installation process
...
}
```
Eg. For example, to configure an access policy for the BMS service, whose service registered with Samgr is **bundlems** and whose registered feature is **BmsFeature**, perform the following operations:
**IPC authentication for a mini or small system**
1. Define feature policies. You can configure multiple features and configure multiple access policies for each feature.
This section uses the bundle manager as an example to describe how to configure access policies for APIs provided by the IPC authentication component. In this example, the service registered by BMS with Samgr is **bundlems**, and the feature registered for open APIs is **BmsFeature**.
**Figure 1** Example feature policy<a name="fig715515221920"></a>
1. <a name="li15901515152517"></a>Configure access policies in the **base/security/permission/services/permission\_lite/ipc\_auth/include/policy\_preset.h** file. Access policies are classified into the following three types:
1. **RANGE**: Processes with a specified range of UIDs can access BMS APIs. **uidMin** and **uidMax** must be specified.
2. **FIXED**: Processes with specified UIDs can access BMS APIs. **fixedUid** must be specified, and a maximum of eight UIDs are allowed.
3. **BUNDLENAME**: An app with a specified **bundleName** can access BMS APIs.
```
FeaturePolicy bmsFeature[] = {
{
"BmsFeature",
{
{
.type=FIXED, // Processes with specified UIDs can access BMS APIs.
.fixedUid={2, 3, 8}
},
{
.type=RANGE, // Processes with a specified range of UIDs can access BMS APIs.
.uidMin=100,
.uidMax=__INT_MAX__,
},
}
},
{
"BmsInnerFeature",
{
{
.type=FIXED, // Processes with specified UIDs can access BMS APIs.
.fixedUid={2, 3, 8}
},
{
.type=RANGE,
.uidMin=100,
.uidMax=999,
},
}
},
};
```
2. Add the policies configured for the features in [Step 1](#li15901515152517) to the global policy settings. You need to set the number of features.
```
static PolicySetting g_presetPolicies[] = {
{"permissionms", pmsFeature, 1},
{"abilityms", amsFeature, 2},
{"bundlems", bmsFeature, 2}, // Add the policies configured for the two features in [Step 1](#li15901515152517) to the global policy settings.
{"dtbschedsrv", dmsFeature, 1},
{"samgr", samgrFeature, 1},
{"appspawn", appspawnFeature, 1},
{"WMS", wmsFeature, 1},
{"bundle_daemon", bdsFeature, 1},
};
```
3. Register the **BmsFeature** defined in [Step 1](#li15901515152517) with Samgr.
```
const char BMS_SERVICE[] = "bundlems";
const char BMS_FEATURE[] = "BmsFeature";
static void Init()
{
SamgrLite *sm = SAMGR_GetInstance();
if (sm == nullptr) {
return;
}
// Register the BmsFeature with Samgr.
sm->RegisterFeature(BMS_SERVICE, reinterpret_cast<Feature *>(BundleMsFeature::GetInstance()));
sm->RegisterFeatureApi(BMS_SERVICE, BMS_FEATURE,
GetBmsFeatureApi(reinterpret_cast<Feature *>(BundleMsFeature::GetInstance())));
HILOG_DEBUG(HILOG_MODULE_APP, "BundleMS feature start success");
}
APP_FEATURE_INIT(Init);
```
![](figures/bms策略举例.png)
When you register a service with Samgr, Samgr calls the **GetCommunicationStrategy** function of the IPC authentication component to obtain access policies of the service. When other services or apps access this service through IPC, Samgr calls the **IsCommunicationAllowed** function of the IPC authentication component to check whether the services or apps have the access permission.
There are three types of access policies:
**Figure 2** Access policy structure<a name="fig1848524515915"></a>
![](figures/策略类型2.png)
1. **RANGE**: Processes with UIDs in a specified range can access the BMS service. **uidMin** and **uidMax** must be specified.
2. **FIXED**: Processes with specified UIDs can access the BMS service. **fixedUid** must be specified, and a maximum of eight UIDs are allowed.
3. **BUNDLENAME**: A specified application can access the BMS service. **bundleName** must be specified.
2. Add the defined feature policies to the global policy. You need to configure the number of features.
**Figure 3** Registering a feature policy<a name="fig1181753551014"></a>
![](figures/全局策略2.png)
UID allocation rules:
1. Init process: 0
2. appspawn process: 1
3. Shell process: 2
4. Other built-in system services: less than or equal to 99
5. System applications \(such as settings, home screen, and camera\): 100999
6. Preset applications: 10009999
7. Common third-party applications: 10000 to **INT\_MAX**
## Repositories Involved<a name="section1371113476307"></a>
security
security\_permission

View File

@ -1,104 +1,369 @@
# 项目介绍<a name="ZH-CN_TOPIC_0000001123217533"></a>
# 应用权限管理<a name="ZH-CN_TOPIC_0000001101239136"></a>
- [应用权限管理](#section20822104317111)
- [IPC通信鉴权](#section156859591110)
- [简介](#section11660541593)
- [目录](#section161941989596)
- [约束](#section119744591305)
- [使用](#section137768191623)
- [接口说明](#section1551164914237)
- [使用说明](#section129654513264)
## 应用权限管理<a name="section20822104317111"></a>
- [相关仓](#section1371113476307)
应用权限是软件用来访问系统资源和使用系统能力的一种通行方式,存在涉及个人隐私相关功能和数据的场景,例如:访问个人设备的硬件特性,如摄像头、麦克风,以及读写媒体文件等。操作系统通过应用权限管理来保护这些数据以及能力。
## 简介<a name="section11660541593"></a>
权限定义字段说明:
OpenHarmony中应用和系统服务均运行在独立的沙箱中进程空间和程序数据都是相互隔离的以保护应用数据的安全性但是运行在独立沙箱中的服务或应用同时需要对外提供一些API以实现所需功能其他独立沙箱中的应用在跨进程访问这些API时需要系统提供一种权限管理机制对这些API的访问者进行授权。
<a name="table1073153511418"></a>
<table><thead align="left"><tr id="row11107193541417"><th class="cellrowborder" valign="top" width="22.220000000000002%" id="mcps1.1.4.1.1"><p id="p6107535141420"><a name="p6107535141420"></a><a name="p6107535141420"></a>字段</p>
- 应用权限管理提供了权限定义机制允许系统服务和应用为自己的敏感API定义新的权限其他应用必须申请此权限才能访问此敏感API
- 应用权限管理提供了权限申请机制允许应用申请权限这些权限由系统或者其他应用定义权限申请通过后就能访问这个权限相关的系统或其他应用提供的敏感API
- 应用权限管理也为用户提供了一些必须的功能,方便用户查看和管理权限授予情况。
**图 1** 应用权限管理架构<a name="fig4460722185514"></a>
![](figures/zh-cn_image_0000001113598272.png)
应用权限管理为用户程序框架子系统提供权限管理功能,并且为上层应用提供权限申请和授权状态查询接口。本次开源的应用权限管理功能适用于大型系统和标准系统。
- 轻量系统mini system面向MCU类处理器例如Arm Cortex-M、RISC-V 32位的设备硬件资源极其有限参考内存≥128KB可以提供多种轻量级网络协议轻量级的图形框架以及丰富的IOT总线读写部件等。可支撑的产品如智能家居领域的连接类模组、传感器设备、穿戴类设备等。
- 小型系统small system面向应用处理器例如Arm Cortex-A的设备参考内存≥1MB可以提供更高的安全能力、标准的图形框架、视频编解码的多媒体能力。可支撑的产品如智能家居领域的IP Camera、电子猫眼、路由器以及智慧出行域的行车记录仪等。
- 标准系统standard system面向应用处理器例如Arm Cortex-A的设备参考内存≥128MB可以提供增强的交互能力、3D GPU以及硬件合成能力、更多控件以及动效更丰富的图形能力、完整的应用框架。可支撑的产品如高端的冰箱显示屏。
## 目录<a name="section161941989596"></a>
```
/base/security/permission
├── frameworks # 基础设施层
│ └── permission_standard # 标准系统权限管理基础设施层
├── interfaces # 接口层
│ ├── innerkits # 内部接口层
│ │ ├── permission_lite # 轻量系统、小型系统权限管理内部接口层
│ │ └── permission_standard # 标准系统权限管理内部接口层
│ └── kits # 外部接口层
│ ├── permission_lite # 轻量系统、小型系统权限管理外部接口层
│ └── permission_standard # 标准系统权限管理外部接口层
└── services # 服务层
├── permission_lite # 轻量系统、小型系统权限管理服务层
└── permission_standard # 标准系统权限管理服务层
```
## 约束<a name="section119744591305"></a>
- 标准系统应用权限管理本期仅提供本地权限管理的C++接口,不涉及分布式权限管理。
## 使用<a name="section137768191623"></a>
### 接口说明<a name="section1551164914237"></a>
**标准系统应用权限管理**此模块主要为标准系统用户程序框架子系统提供权限管理基础校验能力不对三方app开放并提供如下API
<a name="table17351104911243"></a>
<table><thead align="left"><tr id="row43512497244"><th class="cellrowborder" valign="top" width="73.41%" id="mcps1.1.3.1.1"><p id="p8351104918247"><a name="p8351104918247"></a><a name="p8351104918247"></a>接口名</p>
</th>
<th class="cellrowborder" valign="top" width="35.099999999999994%" id="mcps1.1.4.1.2"><p id="p111080352143"><a name="p111080352143"></a><a name="p111080352143"></a>取值</p>
</th>
<th class="cellrowborder" valign="top" width="42.68%" id="mcps1.1.4.1.3"><p id="p161080358141"><a name="p161080358141"></a><a name="p161080358141"></a>意义</p>
<th class="cellrowborder" valign="top" width="26.590000000000003%" id="mcps1.1.3.1.2"><p id="p7351174913247"><a name="p7351174913247"></a><a name="p7351174913247"></a>说明</p>
</th>
</tr>
</thead>
<tbody><tr id="row151081735111418"><td class="cellrowborder" valign="top" width="22.220000000000002%" headers="mcps1.1.4.1.1 "><p id="p1108193521417"><a name="p1108193521417"></a><a name="p1108193521417"></a>name</p>
<tbody><tr id="row143511494244"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p2504174918322"><a name="p2504174918322"></a><a name="p2504174918322"></a>int VerifyPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="35.099999999999994%" headers="mcps1.1.4.1.2 "><p id="p131081435151413"><a name="p131081435151413"></a><a name="p131081435151413"></a>字符串</p>
</td>
<td class="cellrowborder" valign="top" width="42.68%" headers="mcps1.1.4.1.3 "><p id="p0108235141411"><a name="p0108235141411"></a><a name="p0108235141411"></a>权限名。</p>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p14504549163217"><a name="p14504549163217"></a><a name="p14504549163217"></a>校验应用是否已授予对应的权限</p>
</td>
</tr>
<tr id="row19108143516148"><td class="cellrowborder" valign="top" width="22.220000000000002%" headers="mcps1.1.4.1.1 "><p id="p51081355145"><a name="p51081355145"></a><a name="p51081355145"></a>reason</p>
<tr id="row217303717326"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p8504849123210"><a name="p8504849123210"></a><a name="p8504849123210"></a>bool CanRequestPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="35.099999999999994%" headers="mcps1.1.4.1.2 "><p id="p01082358147"><a name="p01082358147"></a><a name="p01082358147"></a>多语言字符串id</p>
</td>
<td class="cellrowborder" valign="top" width="42.68%" headers="mcps1.1.4.1.3 "><p id="p191081235171414"><a name="p191081235171414"></a><a name="p191081235171414"></a>应用申请此权限的目的。</p>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p850417499329"><a name="p850417499329"></a><a name="p850417499329"></a>判断应用是否需要弹框申请权限</p>
</td>
</tr>
<tr id="row13108123516145"><td class="cellrowborder" valign="top" width="22.220000000000002%" headers="mcps1.1.4.1.1 "><p id="p18109835101415"><a name="p18109835101415"></a><a name="p18109835101415"></a>used-scene{</p>
<p id="p910913358146"><a name="p910913358146"></a><a name="p910913358146"></a>ability</p>
<p id="p11109235181420"><a name="p11109235181420"></a><a name="p11109235181420"></a>when</p>
<p id="p16109193531417"><a name="p16109193531417"></a><a name="p16109193531417"></a>}</p>
<tr id="row677573713220"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p16504124933210"><a name="p16504124933210"></a><a name="p16504124933210"></a>int GrantUserGrantedPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="35.099999999999994%" headers="mcps1.1.4.1.2 "><p id="p4109123511420"><a name="p4109123511420"></a><a name="p4109123511420"></a>ability:组件类名字符串</p>
<p id="p19109133531410"><a name="p19109133531410"></a><a name="p19109133531410"></a>when:inuse, always</p>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p115042494327"><a name="p115042494327"></a><a name="p115042494327"></a>授予应用对应的user_grant权限</p>
</td>
<td class="cellrowborder" valign="top" width="42.68%" headers="mcps1.1.4.1.3 "><p id="p31091835151413"><a name="p31091835151413"></a><a name="p31091835151413"></a>调用受此权限管控的接口的场景。</p>
<p id="p93361156407"><a name="p93361156407"></a><a name="p93361156407"></a>声明在哪些组件和场景(前台/后台)下调用受管控的接口。</p>
</tr>
<tr id="row722533813329"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p9504114963210"><a name="p9504114963210"></a><a name="p9504114963210"></a>int GrantSystemGrantedPermission(const string&amp; bundleName, const string&amp; permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p850412493329"><a name="p850412493329"></a><a name="p850412493329"></a>授予应用对应的system_grant权限</p>
</td>
</tr>
<tr id="row1354353873216"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p450414919328"><a name="p450414919328"></a><a name="p450414919328"></a>int RevokeUserGrantedPermission(const string&amp; bundleName, const string&amp; permissionName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p1050411498327"><a name="p1050411498327"></a><a name="p1050411498327"></a>撤销应用对应的user_grant权限</p>
</td>
</tr>
<tr id="row1073519380323"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p1850484933212"><a name="p1850484933212"></a><a name="p1850484933212"></a>int RevokeSystemGrantedPermission(const string&amp; bundleName, const string&amp; permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p35048492326"><a name="p35048492326"></a><a name="p35048492326"></a>撤销应用对应的system_grant权限</p>
</td>
</tr>
<tr id="row1692163820325"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p9504134953215"><a name="p9504134953215"></a><a name="p9504134953215"></a>int AddUserGrantedReqPermissions(const string&amp; bundleName, const std::vector&lt;string&gt;&amp; permList, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p250424993212"><a name="p250424993212"></a><a name="p250424993212"></a>添加应用申请的user_grant权限</p>
</td>
</tr>
<tr id="row1890399325"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p1950413498329"><a name="p1950413498329"></a><a name="p1950413498329"></a>int AddSystemGrantedReqPermissions(const string&amp; bundleName, const std::vector&lt;string&gt;&amp; permList)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p1150444943210"><a name="p1150444943210"></a><a name="p1150444943210"></a>添加应用申请的system_grant权限</p>
</td>
</tr>
<tr id="row13257153973215"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p2505184917329"><a name="p2505184917329"></a><a name="p2505184917329"></a>int RemoveUserGrantedReqPermissions(const string&amp; bundleName, int userId)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p950514973212"><a name="p950514973212"></a><a name="p950514973212"></a>移除应用申请的所有user_grant权限</p>
</td>
</tr>
<tr id="row144437398322"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p205051049103214"><a name="p205051049103214"></a><a name="p205051049103214"></a>int RemoveSystemGrantedReqPermissions(const string&amp; bundleName)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p125051349123213"><a name="p125051349123213"></a><a name="p125051349123213"></a>移除应用申请的所有system_grant权限</p>
</td>
</tr>
<tr id="row13617183915329"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p16505049173217"><a name="p16505049173217"></a><a name="p16505049173217"></a>int AddDefPermissions(const std::vector&lt;PermissionDef&gt;&amp; permList)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p13505849103215"><a name="p13505849103215"></a><a name="p13505849103215"></a>添加应用定义的权限</p>
</td>
</tr>
<tr id="row117857394324"><td class="cellrowborder" valign="top" width="73.41%" headers="mcps1.1.3.1.1 "><p id="p105059492325"><a name="p105059492325"></a><a name="p105059492325"></a>int GetDefPermission(const string&amp; permissionName, PermissionDef&amp; permissionDefResult)</p>
</td>
<td class="cellrowborder" valign="top" width="26.590000000000003%" headers="mcps1.1.3.1.2 "><p id="p11505349103220"><a name="p11505349103220"></a><a name="p11505349103220"></a>获取指定权限名的权限定义信息</p>
</td>
</tr>
</tbody>
</table>
## IPC通信鉴权<a name="section156859591110"></a>
**轻量系统、小型系统应用权限管理**当前仅供系统应用和系统服务调用具体API接口如下
- 在Samgr中注册的系统服务如果通过进程间通信的方式暴露接口给其他进程访问需要配置相应的访问控制策略。若不进行相关配置访问会被拒绝。
- 配置方式在头文件base/security/permission/services/permission\_lite/ipc\_auth/include/policy\_preset.h中配置访问策略。
<a name="table9789027162518"></a>
<table><thead align="left"><tr id="row9789427112518"><th class="cellrowborder" valign="top" width="55.66%" id="mcps1.1.3.1.1"><p id="p9790102717251"><a name="p9790102717251"></a><a name="p9790102717251"></a>接口名</p>
</th>
<th class="cellrowborder" valign="top" width="44.34%" id="mcps1.1.3.1.2"><p id="p779032715251"><a name="p779032715251"></a><a name="p779032715251"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row187901627112516"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p138014275353"><a name="p138014275353"></a><a name="p138014275353"></a>int CheckPermission(int uid, const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p57901727202510"><a name="p57901727202510"></a><a name="p57901727202510"></a>检查指定UID的应用进程是否具有访问系统服务API的权限</p>
</td>
</tr>
<tr id="row19341734164410"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p123453412448"><a name="p123453412448"></a><a name="p123453412448"></a>int CheckSelfPermission(const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p937645212447"><a name="p937645212447"></a><a name="p937645212447"></a>检查调用者是否具有访问系统服务API的权限</p>
</td>
</tr>
<tr id="row879032715258"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p13071135133514"><a name="p13071135133514"></a><a name="p13071135133514"></a>int QueryPermission(const char *identifier, PermissionSaved **permissions, int *permNum)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p1379072718259"><a name="p1379072718259"></a><a name="p1379072718259"></a>查询应用申请的所有权限,并检查权限是否被授予</p>
</td>
</tr>
<tr id="row877239193516"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p878133903516"><a name="p878133903516"></a><a name="p878133903516"></a>int GrantPermission(const char *identifier, const char *permName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p678143943515"><a name="p678143943515"></a><a name="p678143943515"></a>将指定权限授予应用程序</p>
</td>
</tr>
<tr id="row3616164223510"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p1617142163517"><a name="p1617142163517"></a><a name="p1617142163517"></a>int RevokePermission(const char *identifier, const char *permName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p06171242143517"><a name="p06171242143517"></a><a name="p06171242143517"></a>收回应用程序的指定权限</p>
</td>
</tr>
<tr id="row13790122742516"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p23273123365"><a name="p23273123365"></a><a name="p23273123365"></a>int GrantRuntimePermission(int uid, const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p177908273259"><a name="p177908273259"></a><a name="p177908273259"></a>应用运行时动态授予指定权限</p>
</td>
</tr>
<tr id="row18566191217452"><td class="cellrowborder" valign="top" width="55.66%" headers="mcps1.1.3.1.1 "><p id="p169891916194512"><a name="p169891916194512"></a><a name="p169891916194512"></a>int RevokeRuntimePermission(int uid, const char *permissionName)</p>
</td>
<td class="cellrowborder" valign="top" width="44.34%" headers="mcps1.1.3.1.2 "><p id="p937132011440"><a name="p937132011440"></a><a name="p937132011440"></a>应用运行时动态撤销指定权限</p>
</td>
</tr>
</tbody>
</table>
1. 定义各个Feature的策略
**轻量系统、小型系统IPC通信鉴权**
2. 将Feature的策略加到全局策略中
<a name="table10494122145517"></a>
<table><thead align="left"><tr id="row1494152195511"><th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.1"><p id="p14941221135515"><a name="p14941221135515"></a><a name="p14941221135515"></a>接口名</p>
</th>
<th class="cellrowborder" valign="top" width="50%" id="mcps1.1.3.1.2"><p id="p8494172116555"><a name="p8494172116555"></a><a name="p8494172116555"></a>描述</p>
</th>
</tr>
</thead>
<tbody><tr id="row1849482118555"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p1414381815720"><a name="p1414381815720"></a><a name="p1414381815720"></a>int GetCommunicationStrategy(RegParams params, PolicyTrans **policies, unsigned int *policyNum)</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p749582195510"><a name="p749582195510"></a><a name="p749582195510"></a>服务注册过程中查询调用接口对应的访问策略仅供Samgr调用</p>
</td>
</tr>
<tr id="row8495521115517"><td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.1 "><p id="p966319247576"><a name="p966319247576"></a><a name="p966319247576"></a>int IsCommunicationAllowed(AuthParams params)</p>
</td>
<td class="cellrowborder" valign="top" width="50%" headers="mcps1.1.3.1.2 "><p id="p134951921115511"><a name="p134951921115511"></a><a name="p134951921115511"></a>检查访问主体进程是否有权限调用受访客体进程的接口仅供Samgr调用</p>
</td>
</tr>
</tbody>
</table>
### 使用说明<a name="section129654513264"></a>
**标准系统应用权限管理**
使用说明所有接口均为内部接口仅提供底层能力不对开发者开放。鉴权过程中直接调用VerifyPermission接口即可。
1. 明确要校验应用的UID及需要校验的权限名称permissionName
2. 根据UID获取应用的包名 bundleName
3. 根据UID获取应用的用户ID userId
4. 将需要校验的权限名permissionName, 包名bundleName和userId传入接口VerifyPermission\(string permissionName, string bundleName, int userId\)
5. 得到校验结果
**轻量系统、小型系统应用权限管理**
使用说明以包管理器的应用权限开发为例进行讲解。开发过程中首先需要明确涉及的敏感权限并在config.json中声明该权限在安装应用程序时包管理器会调用应用权限管理组件的接口检查该权限是否被授予若授予安装流程正常进行否则安装失败。
1. 在开发过程中包管理器明确需要安装应用的权限ohos.permission.INSTALL\_BUNDLE并在config.json中声明该权限
```
{
...
"module": {
"package": "ohos.demo.kitframework",
"deviceType": [
"phone", "tv","tablet", "pc","car","smartWatch","sportsWatch","smartCamera", "smartVision"
],
"reqPermissions": [{
// 声明需要的权限:安装应用程序的权限名
"name": "ohos.permission.INSTALL_BUNDLE",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
},
{
"name": "ohos.permission.LISTEN_BUNDLE_CHANGE",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
},
{
"name": "ohos.permission.GET_BUNDLE_INFO",
"reason": "install bundle",
"usedScene": {
"ability": [
"KitFramework"
],
"when": "always"
}
}
],
...
}
```
2. 当包管理器开发应用安装功能接口时,会调用权限管理相关接口检查自身是否具有安装应用程序的权限,例如:以安装应用的权限名"ohos.permission.INSTALL\_BUNDLE"作为入参调用CheckPermission接口检查包管理器是否具有安装应用的权限如果有权限安装流程继续执行否则返回安装失败
```
constexpr static char PERMISSION_INSTALL_BUNDLE[] = "ohos.permission.INSTALL_BUNDLE";
bool Install(const char *hapPath, const InstallParam *installParam, InstallerCallback installerCallback)
{
if ((hapPath == nullptr) || (installerCallback == nullptr) || (installParam == nullptr)) {
HILOG_ERROR(HILOG_MODULE_APP, "BundleManager install failed due to nullptr parameters");
return false;
}
// 检查ohos.permission.INSTALL_BUNDLE权限是否被授予
if (CheckPermission(0, static_cast<const char *>(PERMISSION_INSTALL_BUNDLE)) != GRANTED) {
HILOG_ERROR(HILOG_MODULE_APP, "BundleManager install failed due to permission denied");
return false; // 返回安装失败
}
// 安装流程
...
}
```
Eg. 比如当前需要为BMS服务配置访问策略BMS在Samgr中注册的service为bundlems注册的Feature为BmsFeature。
**轻量系统、小型系统IPC通信鉴权**
一、首先定义Feature的策略可配置多个Feature每个Feature可以配置多个访问策略策略的声明方式参考图1
使用说明以BMS服务通过IPC通信方式对外开放接口为例讲解如何通过IPC通信鉴权组件配置对应接口的访问策略。这里BMS在Samgr中注册的service为bundlems为开放的接口注册的Feature为BmsFeature。
**图 1** Feature策略示例<a name="fig715515221920"></a>
1. 在源码路径下的头文件base/security/permission/services/permission\_lite/ipc\_auth/include/policy\_preset.h中配置相应的访问策略访问策略主要有三种类型
1type为RANGE类型允许某个特定范围UID的进程访问需要指定uidMin和uidMax
2type为FIXED类型允许指定的几个UID的进程访问需要指定fixedUid最多配置8个
3type为BUNDLENAME类型只允许特定的应用访问需要指定bundleName包名
```
FeaturePolicy bmsFeature[] = {
{
"BmsFeature",
{
{
.type=FIXED, // 允许指定UID的进程访问的方式
.fixedUid={2, 3, 8}
},
{
.type=RANGE, // 允许特定范围内的UID的进程访问的方式
.uidMin=100,
.uidMax=__INT_MAX__,
},
}
},
{
"BmsInnerFeature",
{
{
.type=FIXED, // 允许指定UID的进程访问的方式
.fixedUid={2, 3, 8}
},
{
.type=RANGE,
.uidMin=100,
.uidMax=999,
},
}
},
};
```
2. 将步骤1中定义的Feature的策略加配到全局策略中需要配置feature数量
```
static PolicySetting g_presetPolicies[] = {
{"permissionms", pmsFeature, 1},
{"abilityms", amsFeature, 2},
{"bundlems", bmsFeature, 2}, // 步骤1定义的BMS的feature数量为2
{"dtbschedsrv", dmsFeature, 1},
{"samgr", samgrFeature, 1},
{"appspawn", appspawnFeature, 1},
{"WMS", wmsFeature, 1},
{"bundle_daemon", bdsFeature, 1},
};
```
3. 将步骤1中定义的BmsFeature注册到Samgr
```
const char BMS_SERVICE[] = "bundlems";
const char BMS_FEATURE[] = "BmsFeature";
static void Init()
{
SamgrLite *sm = SAMGR_GetInstance();
if (sm == nullptr) {
return;
}
// 注册服务到Samgr
sm->RegisterFeature(BMS_SERVICE, reinterpret_cast<Feature *>(BundleMsFeature::GetInstance()));
sm->RegisterFeatureApi(BMS_SERVICE, BMS_FEATURE,
GetBmsFeatureApi(reinterpret_cast<Feature *>(BundleMsFeature::GetInstance())));
HILOG_DEBUG(HILOG_MODULE_APP, "BundleMS feature start success");
}
APP_FEATURE_INIT(Init);
```
![](figures/bms策略举例.png)
完成以上开发步骤后开发者在Samgr注册服务时Samgr会调用IPC通信鉴权组件的GetCommunicationStrategy接口获取服务的访问策略当其他服务或应用通过IPC方式访问这些服务时Samgr会调用IPC通信鉴权组件的IsCommunicationAllowed接口检查调用者服务的权限如果满足访问策略则可以访问开发者接口否则拒绝访问。
访问策略有三种类型:
**图 2** 访问策略结构体<a name="fig1848524515915"></a>
![](figures/策略类型2.png)
1. type为RANGE类型允许某个特定范围UID的进程访问需要指定uidMin和uidMax
2. type为FIXED类型允许指定的几个UID的进程访问需要指定fixedUid最多配置8个
3. type为BUNDLENAME类型只允许特定的应用访问需要指定bundleName包名
二、将定义的Feature的策略加配到全局策略中需要配置feature数量注册参考图3
**图 3** feature策略注册<a name="fig1181753551014"></a>
![](figures/全局策略2.png)
UID分配规则
1. Init进程0
2. appspawn进程1
3. Shell进程2
4. 其他内置系统服务UID <= 99
5. 系统应用如设置、桌面、相机100 \~ 999
6. 预置厂商应用1000 \~ 9999
7. 普通三方应用10000 \~ INT\_MAX
## 相关仓<a name="section1371113476307"></a>
安全子系统
security\_permission

Binary file not shown.

Before

Width:  |  Height:  |  Size: 12 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 23 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 9.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.1 KiB

View File

@ -0,0 +1,43 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos.gni")
################################################################
# C++, Main source file here.
################################################################
config("permission_standard_communication_adapter_cxx_public_config") {
visibility = [ ":*" ]
include_dirs = [ "main/cpp/include" ]
}
ohos_shared_library("permission_standard_communication_adapter_cxx") {
subsystem_name = "security"
part_name = "permission_standard"
public_configs =
[ ":permission_standard_communication_adapter_cxx_public_config" ]
include_dirs = [
"main/cpp/include",
"main/cpp/src",
"//utils/native/base/include",
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission",
]
sources = [ "main/cpp/src/permission_def_parcel.cpp" ]
deps = [ "//utils/native/base:utils" ]
external_deps = [ "ipc:ipc_core" ]
}

View File

@ -0,0 +1,85 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef I_PERMISSION_MANAGER_H
#define I_PERMISSION_MANAGER_H
#include <string>
#include "permission_def_parcel.h"
#include "iremote_broker.h"
#include "errors.h"
namespace OHOS {
namespace Security {
namespace Permission {
class IPermissionManager : public IRemoteBroker {
public:
static const int SA_ID_PERMISSION_MANAGER_SERVICE = 3501;
DECLARE_INTERFACE_DESCRIPTOR(u"ohos.security.permission.IPermissionManager");
virtual int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) = 0;
virtual bool CanRequestPermission(const std::string& bundleName, const std::string& permissionName, int userId) = 0;
virtual int GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) = 0;
virtual int GrantSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) = 0;
virtual int RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) = 0;
virtual int RevokeSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) = 0;
virtual int AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId) = 0;
virtual int AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList) = 0;
virtual int RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId) = 0;
virtual int RemoveSystemGrantedReqPermissions(const std::string& bundleName) = 0;
virtual int AddDefPermissions(const std::vector<PermissionDefParcel>& permDefList) = 0;
virtual int RemoveDefPermissions(const std::string& bundleName) = 0;
virtual int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) = 0;
enum class InterfaceCode {
VERIFY_PERMISSION = 0xff01,
CAN_REQUEST_PERMISSION = 0xff02,
GRANT_USER_GRANTED_PERMISSION = 0xff03,
GRANT_SYSTEM_GRANTED_PERMISSION = 0xff04,
REVOKE_USER_GRANTED_PERMISSION = 0xff05,
REVOKE_SYSTEM_GRANTED_PERMISSION = 0xff06,
ADD_USER_GRANTED_REQ_PERMISSIONS = 0xff07,
ADD_SYSTEM_GRANTED_REQ_PERMISSIONS = 0xff08,
REMOVE_USER_GRANTED_REQ_PERMISSIONS = 0xff09,
REMOVE_SYSTEM_GRANTED_REQ_PERMISSIONS = 0xff10,
ADD_DEF_PERMISSIONS = 0xff11,
REMOVE_DEF_PERMISSIONS = 0xff12,
GET_DEF_PERMISSION = 0xff13,
};
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // I_PERMISSION_MANAGER_H

View File

@ -0,0 +1,40 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_DEF_PARCEL_H
#define PERMISSION_DEF_PARCEL_H
#include "permission_def.h"
#include "parcel.h"
namespace OHOS {
namespace Security {
namespace Permission {
struct PermissionDefParcel final : public Parcelable {
PermissionDefParcel() = default;
~PermissionDefParcel() override = default;
bool Marshalling(Parcel& out) const override;
static PermissionDefParcel* Unmarshalling(Parcel& in);
PermissionDef permissionDef;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_DEF_PARCEL_H

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_def_parcel.h"
namespace OHOS {
namespace Security {
namespace Permission {
#define RETURN_IF_FALSE(expr) \
if (!(expr)) { \
return false; \
}
#define RELEASE_IF_FALSE(expr, obj) \
if (!(expr)) { \
delete (obj); \
(obj) = nullptr; \
return (obj); \
}
bool PermissionDefParcel::Marshalling(Parcel& out) const
{
RETURN_IF_FALSE(out.WriteString(this->permissionDef.permissionName));
RETURN_IF_FALSE(out.WriteString(this->permissionDef.bundleName));
RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.grantMode));
RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.availableScope));
RETURN_IF_FALSE(out.WriteString(this->permissionDef.label));
RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.labelId));
RETURN_IF_FALSE(out.WriteString(this->permissionDef.description));
RETURN_IF_FALSE(out.WriteInt32(this->permissionDef.descriptionId));
return true;
}
PermissionDefParcel* PermissionDefParcel::Unmarshalling(Parcel& in)
{
auto* permissionDefParcel = new (std::nothrow) PermissionDefParcel();
RELEASE_IF_FALSE(permissionDefParcel != nullptr, permissionDefParcel);
permissionDefParcel->permissionDef.permissionName = in.ReadString();
permissionDefParcel->permissionDef.bundleName = in.ReadString();
RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.grantMode), permissionDefParcel);
RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.availableScope), permissionDefParcel);
permissionDefParcel->permissionDef.label = in.ReadString();
RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.labelId), permissionDefParcel);
permissionDefParcel->permissionDef.description = in.ReadString();
RELEASE_IF_FALSE(in.ReadInt32(permissionDefParcel->permissionDef.descriptionId), permissionDefParcel);
return permissionDefParcel;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,38 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos.gni")
################################################################
# C++, Main source file here.
################################################################
config("permission_standard_infrastructure_cxx_public_config") {
visibility = [ ":*" ]
include_dirs = [ "main/cpp/include" ]
}
ohos_shared_library("permission_standard_infrastructure_cxx") {
subsystem_name = "security"
part_name = "permission_standard"
public_configs = [ ":permission_standard_infrastructure_cxx_public_config" ]
include_dirs = []
sources = [ "main/cpp/src/data_validator.cpp" ]
deps = [ "//utils/native/base:utils" ]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
cflags_cc = [ "-DHILOG_ENABLE" ]
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include <string>
#ifndef DATA_VALIDATOR_H
#define DATA_VALIDATOR_H
namespace OHOS {
namespace Security {
namespace Permission {
class DataValidator final {
public:
static bool IsBundleNameValid(const std::string& bundleName);
static bool IsPermissionNameValid(const std::string& permissionName);
static bool IsUserIdValid(const int userId);
private:
const static int MAX_LENGTH = 256;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // DATA_VALIDATOR_H

View File

@ -0,0 +1,63 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_LOG_H
#define PERMISSION_LOG_H
#ifdef HILOG_ENABLE
#include "hilog/log.h"
#ifndef __cplusplus
#define PERMISSION_LOG_DEBUG(fmt, ...) HILOG_DEBUG(LOG_CORE, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_INFO(fmt, ...) HILOG_INFO(LOG_CORE, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_WARN(fmt, ...) HILOG_WARN(LOG_CORE, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_ERROR(fmt, ...) HILOG_ERROR(LOG_CORE, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_FATAL(fmt, ...) HILOG_FATAL(LOG_CORE, fmt, ##__VA_ARGS__)
#else
#define PERMISSION_LOG_DEBUG(label, fmt, ...) OHOS::HiviewDFX::HiLog::Debug(label, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_INFO(label, fmt, ...) OHOS::HiviewDFX::HiLog::Info(label, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_WARN(label, fmt, ...) OHOS::HiviewDFX::HiLog::Warn(label, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_ERROR(label, fmt, ...) OHOS::HiviewDFX::HiLog::Error(label, fmt, ##__VA_ARGS__)
#define PERMISSION_LOG_FATAL(label, fmt, ...) OHOS::HiviewDFX::HiLog::Fatal(label, fmt, ##__VA_ARGS__)
#endif // __cplusplus
/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */
#undef LOG_TAG
#undef LOG_DOMAIN
static constexpr unsigned int SECURITY_DOMAIN_PERMISSION = 0xD002F01;
#else
#include <stdarg.h>
#include <stdio.h>
/* define LOG_TAG as "security_*" at your submodule, * means your submodule name such as "security_dac" */
#undef LOG_TAG
#define PERMISSION_LOG_DEBUG(fmt, ...) printf("[%s] debug: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__)
#define PERMISSION_LOG_INFO(fmt, ...) printf("[%s] info: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__)
#define PERMISSION_LOG_WARN(fmt, ...) printf("[%s] warn: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__)
#define PERMISSION_LOG_ERROR(fmt, ...) printf("[%s] error: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__)
#define PERMISSION_LOG_FATAL(fmt, ...) printf("[%s] fatal: %s: " fmt "\n", LOG_TAG, __func__, ##__VA_ARGS__)
#endif // HILOG_ENABLE
#endif // PERMISSION_LOG_H

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef TEST_CONST_H
#define TEST_CONST_H
#include <string>
namespace OHOS {
namespace Security {
namespace Permission {
static const std::string TEST_BUNDLE_NAME = "ohos";
static const std::string TEST_PERMISSION_NAME_ALPHA = "ohos.permission.ALPHA";
static const std::string TEST_PERMISSION_NAME_BETA = "ohos.permission.BETA";
static const std::string TEST_PERMISSION_NAME_GAMMA = "ohos.permission.GAMMA";
static const std::string TEST_LABEL = "test label";
static const std::string TEST_DESCRIPTION = "test description";
static const int TEST_LABEL_ID = 9527;
static const int TEST_DESCRIPTION_ID = 9528;
static const int TEST_INVALID_USER_ID = -1;
static const int TEST_USER_ID = 0;
static const int TEST_SUB_USER_ID = 10;
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // TEST_CONST_H

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "data_validator.h"
namespace OHOS {
namespace Security {
namespace Permission {
bool DataValidator::IsBundleNameValid(const std::string& bundleName)
{
return !bundleName.empty() && (bundleName.length() <= MAX_LENGTH);
}
bool DataValidator::IsPermissionNameValid(const std::string& permissionName)
{
return !permissionName.empty() && (permissionName.length() <= MAX_LENGTH);
}
bool DataValidator::IsUserIdValid(const int userId)
{
return userId >= 0;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

View File

@ -0,0 +1,58 @@
# Copyright (C) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos.gni")
################################################################
# C++, Main, source file here.
################################################################
config("permission_sdk_cxx_public_config_standard") {
visibility = [ ":*" ]
include_dirs = [ "main/cpp/include" ]
}
ohos_shared_library("libpermissionsdk_standard") {
subsystem_name = "security"
part_name = "permission_standard"
output_name = "libpermissionsdk_standard"
public_configs = [ ":permission_sdk_cxx_public_config_standard" ]
include_dirs = [
"//utils/native/base/include",
"main/cpp/include",
"main/cpp/src",
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission",
]
sources = [
"main/cpp/src/permission/permission_kit.cpp",
"main/cpp/src/permission/permission_manager_client.cpp",
"main/cpp/src/permission/permission_manager_proxy.cpp",
]
deps = [
"//base/security/permission/frameworks/permission_standard/permissioncommunicationadapter:permission_standard_communication_adapter_cxx",
"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"samgr_L2:samgr_proxy",
]
cflags_cc = [ "-DHILOG_ENABLE" ]
}

View File

@ -0,0 +1,46 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_H
#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_H
namespace OHOS {
namespace Security {
namespace Permission {
enum PermissionKitRet {
RET_FAILED = -1,
RET_SUCCESS = 0,
};
typedef enum TypePermissionState {
PERMISSION_NOT_GRANTED = -1,
PERMISSION_GRANTED = 0,
} PermissionState;
typedef enum TypeGrantMode {
USER_GRANT = 0,
SYSTEM_GRANT = 1,
} GrantMode;
typedef enum TypeAvailableScope {
AVAILABLE_SCOPE_ALL = 1 << 0,
AVAILABLE_SCOPE_SIGNATURE = 1 << 1,
AVAILABLE_SCOPE_RESTRICTED = 1 << 2
} AvailableScope;
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // INTERFACES_INNER_KITS_PERMISSION_PERMISSION_H

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_DEF_H
#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_DEF_H
#include <string>
namespace OHOS {
namespace Security {
namespace Permission {
struct PermissionDef {
std::string permissionName;
std::string bundleName;
int grantMode;
int availableScope;
std::string label;
int labelId;
std::string description;
int descriptionId;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // INTERFACES_INNER_KITS_PERMISSION_PERMISSION_DEF_H

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef INTERFACES_INNER_KITS_PERMISSION_PERMISSION_KIT_H
#define INTERFACES_INNER_KITS_PERMISSION_PERMISSION_KIT_H
#include <string>
#include <vector>
#include "permission/permission.h"
#include "permission/permission_def.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionKit {
public:
static int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId);
static bool CanRequestPermission(const std::string& bundleName, const std::string& permissionName, int userId);
static int GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId);
static int GrantSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName);
static int RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId);
static int RevokeSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName);
static int AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId);
static int AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList);
static int RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId);
static int RemoveSystemGrantedReqPermissions(const std::string& bundleName);
static int AddDefPermissions(const std::vector<PermissionDef>& permList);
static int RemoveDefPermissions(const std::string& bundleName);
static int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult);
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif

View File

@ -0,0 +1,142 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission/permission_kit.h"
#include <string>
#include <vector>
#include "permission_log.h"
#include "permission_manager_client.h"
#include "data_validator.h"
namespace OHOS {
namespace Security {
namespace Permission {
using namespace std;
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionKit"};
} // namespace
int PermissionKit::VerifyPermission(const string& bundleName, const string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s, permissionName=%{public}s, userId=%{public}d",
bundleName.c_str(), permissionName.c_str(), userId);
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName) ||
!DataValidator::IsUserIdValid(userId)) {
return PERMISSION_NOT_GRANTED;
}
return PermissionManagerClient::GetInstance().VerifyPermission(bundleName, permissionName, userId);
}
bool PermissionKit::CanRequestPermission(const string& bundleName, const string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s, permissionName=%{public}s, userId=%{public}d",
bundleName.c_str(), permissionName.c_str(), userId);
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName) ||
!DataValidator::IsUserIdValid(userId)) {
return false;
}
return PermissionManagerClient::GetInstance().CanRequestPermission(bundleName, permissionName, userId);
}
int PermissionKit::GrantUserGrantedPermission(const string& bundleName, const string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s, permissionName=%{public}s, userId=%{public}d",
bundleName.c_str(), permissionName.c_str(), userId);
return PermissionManagerClient::GetInstance().GrantUserGrantedPermission(bundleName, permissionName, userId);
}
int PermissionKit::GrantSystemGrantedPermission(const string& bundleName, const string& permissionName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(
LABEL, "bundleName=%{public}s, permissionName=%{public}s", bundleName.c_str(), permissionName.c_str());
return PermissionManagerClient::GetInstance().GrantSystemGrantedPermission(bundleName, permissionName);
}
int PermissionKit::RevokeUserGrantedPermission(const string& bundleName, const string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s, permissionName=%{public}s, userId=%{public}d",
bundleName.c_str(), permissionName.c_str(), userId);
return PermissionManagerClient::GetInstance().RevokeUserGrantedPermission(bundleName, permissionName, userId);
}
int PermissionKit::RevokeSystemGrantedPermission(const string& bundleName, const string& permissionName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(
LABEL, "bundleName=%{public}s, permissionName=%{public}s", bundleName.c_str(), permissionName.c_str());
return PermissionManagerClient::GetInstance().RevokeSystemGrantedPermission(bundleName, permissionName);
}
int PermissionKit::AddUserGrantedReqPermissions(
const string& bundleName, const std::vector<string>& permList, int userId)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId);
return PermissionManagerClient::GetInstance().AddUserGrantedReqPermissions(bundleName, permList, userId);
}
int PermissionKit::AddSystemGrantedReqPermissions(const string& bundleName, const std::vector<string>& permList)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s", bundleName.c_str());
return PermissionManagerClient::GetInstance().AddSystemGrantedReqPermissions(bundleName, permList);
}
int PermissionKit::RemoveUserGrantedReqPermissions(const string& bundleName, int userId)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s, userId=%{public}d", bundleName.c_str(), userId);
return PermissionManagerClient::GetInstance().RemoveUserGrantedReqPermissions(bundleName, userId);
}
int PermissionKit::RemoveSystemGrantedReqPermissions(const string& bundleName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s", bundleName.c_str());
return PermissionManagerClient::GetInstance().RemoveSystemGrantedReqPermissions(bundleName);
}
int PermissionKit::AddDefPermissions(const std::vector<PermissionDef>& permList)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
return PermissionManagerClient::GetInstance().AddDefPermissions(permList);
}
int PermissionKit::RemoveDefPermissions(const string& bundleName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "bundleName=%{public}s", bundleName.c_str());
return PermissionManagerClient::GetInstance().RemoveDefPermissions(bundleName);
}
int PermissionKit::GetDefPermission(const string& permissionName, PermissionDef& permissionDefResult)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called", __func__);
PERMISSION_LOG_INFO(LABEL, "permissionName=%{public}s", permissionName.c_str());
int ret = PermissionManagerClient::GetInstance().GetDefPermission(permissionName, permissionDefResult);
PERMISSION_LOG_INFO(LABEL, "GetDefPermission bundleName = %{public}s", permissionDefResult.bundleName.c_str());
return ret;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,227 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_manager_client.h"
#include "permission.h"
#include "permission_log.h"
#include "iservice_registry.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionManagerClient"};
} // namespace
PermissionManagerClient& PermissionManagerClient::GetInstance()
{
static PermissionManagerClient instance;
return instance;
}
PermissionManagerClient::PermissionManagerClient()
{}
PermissionManagerClient::~PermissionManagerClient()
{}
int PermissionManagerClient::VerifyPermission(
const std::string& bundleName, const std::string& permissionName, int userId) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return PERMISSION_NOT_GRANTED;
}
return proxy->VerifyPermission(bundleName, permissionName, userId);
}
bool PermissionManagerClient::CanRequestPermission(
const std::string& bundleName, const std::string& permissionName, int userId) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return false;
}
return proxy->CanRequestPermission(bundleName, permissionName, userId);
}
int PermissionManagerClient::GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->GrantUserGrantedPermission(bundleName, permissionName, userId);
}
int PermissionManagerClient::GrantSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->GrantSystemGrantedPermission(bundleName, permissionName);
}
int PermissionManagerClient::RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->RevokeUserGrantedPermission(bundleName, permissionName, userId);
}
int PermissionManagerClient::RevokeSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->RevokeSystemGrantedPermission(bundleName, permissionName);
}
int PermissionManagerClient::AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->AddUserGrantedReqPermissions(bundleName, permList, userId);
}
int PermissionManagerClient::AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->AddSystemGrantedReqPermissions(bundleName, permList);
}
int PermissionManagerClient::RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->RemoveUserGrantedReqPermissions(bundleName, userId);
}
int PermissionManagerClient::RemoveSystemGrantedReqPermissions(const std::string& bundleName) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->RemoveSystemGrantedReqPermissions(bundleName);
}
int PermissionManagerClient::AddDefPermissions(const std::vector<PermissionDef>& permDefList) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
std::vector<PermissionDefParcel> parcelList;
for (auto permDef : permDefList) {
PermissionDefParcel parcel;
parcel.permissionDef = permDef;
parcelList.emplace_back(parcel);
}
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) parcelList.size());
return proxy->AddDefPermissions(parcelList);
}
int PermissionManagerClient::RemoveDefPermissions(const std::string& bundleName) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
return proxy->RemoveDefPermissions(bundleName);
}
int PermissionManagerClient::GetDefPermission(
const std::string& permissionName, PermissionDef& permissionDefResult) const
{
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: called!", __func__);
auto proxy = GetProxy();
if (proxy == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: proxy is null", __func__);
return RET_FAILED;
}
PermissionDefParcel permissionDefParcel;
int result = proxy->GetDefPermission(permissionName, permissionDefParcel);
permissionDefResult = permissionDefParcel.permissionDef;
return result;
}
sptr<IPermissionManager> PermissionManagerClient::GetProxy() const
{
auto sam = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
if (sam == nullptr) {
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbilityManager is null", __func__);
return nullptr;
}
auto permissionSa = sam->GetSystemAbility(IPermissionManager::SA_ID_PERMISSION_MANAGER_SERVICE);
if (permissionSa == nullptr) {
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: GetSystemAbility %{public}d is null", __func__,
IPermissionManager::SA_ID_PERMISSION_MANAGER_SERVICE);
return nullptr;
}
auto proxy = iface_cast<IPermissionManager>(permissionSa);
if (proxy == nullptr) {
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: iface_cast get null", __func__);
return nullptr;
}
return proxy;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,72 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_MANAGER_CLIENT_H
#define PERMISSION_MANAGER_CLIENT_H
#include <string>
#include "i_permission_manager.h"
#include "permission/permission_def.h"
#include "nocopyable.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionManagerClient final {
public:
static PermissionManagerClient& GetInstance();
virtual ~PermissionManagerClient();
int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) const;
bool CanRequestPermission(const std::string& bundleName, const std::string& permissionName, int userId) const;
int GrantUserGrantedPermission(const std::string& bundleName, const std::string& permissionName, int userId) const;
int GrantSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) const;
int RevokeUserGrantedPermission(const std::string& bundleName, const std::string& permissionName, int userId) const;
int RevokeSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) const;
int AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId) const;
int AddSystemGrantedReqPermissions(const std::string& bundleName, const std::vector<std::string>& permList) const;
int RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId) const;
int RemoveSystemGrantedReqPermissions(const std::string& bundleName) const;
int AddDefPermissions(const std::vector<PermissionDef>& permDefList) const;
int RemoveDefPermissions(const std::string& bundleName) const;
int GetDefPermission(const std::string& permissionName, PermissionDef& permissionDefResult) const;
private:
PermissionManagerClient();
DISALLOW_COPY_AND_MOVE(PermissionManagerClient);
sptr<IPermissionManager> GetProxy() const;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_MANAGER_CLIENT_H

View File

@ -0,0 +1,482 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_manager_proxy.h"
#include "permission/permission.h"
#include "permission_log.h"
#include "parcel.h"
#include "string_ex.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionManagerProxy"};
}
PermissionManagerProxy::PermissionManagerProxy(const sptr<IRemoteObject>& impl) : IRemoteProxy<IPermissionManager>(impl)
{}
PermissionManagerProxy::~PermissionManagerProxy()
{}
int PermissionManagerProxy::VerifyPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return PERMISSION_NOT_GRANTED;
}
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return PERMISSION_NOT_GRANTED;
}
if (!data.WriteInt32(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__);
return PERMISSION_NOT_GRANTED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return PERMISSION_NOT_GRANTED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::VERIFY_PERMISSION), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return PERMISSION_NOT_GRANTED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
bool PermissionManagerProxy::CanRequestPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return false;
}
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return false;
}
if (!data.WriteInt32(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__);
return false;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return false;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::CAN_REQUEST_PERMISSION), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return false;
}
bool result = reply.ReadBool();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return RET_FAILED;
}
if (!data.WriteInt32(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::GRANT_USER_GRANTED_PERMISSION), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::GrantSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::GRANT_SYSTEM_GRANTED_PERMISSION), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return RET_FAILED;
}
if (!data.WriteInt32(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::REVOKE_USER_GRANTED_PERMISSION), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::RevokeSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult =
remote->SendRequest(static_cast<uint32_t>(IPermissionManager::InterfaceCode::REVOKE_SYSTEM_GRANTED_PERMISSION),
data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteStringVector(permList)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permList", __func__);
return RET_FAILED;
}
if (!data.WriteInt32(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult =
remote->SendRequest(static_cast<uint32_t>(IPermissionManager::InterfaceCode::ADD_USER_GRANTED_REQ_PERMISSIONS),
data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteStringVector(permList)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permList", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::ADD_SYSTEM_GRANTED_REQ_PERMISSIONS), data, reply,
option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
if (!data.WriteInt32(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write userId", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::REMOVE_USER_GRANTED_REQ_PERMISSIONS), data, reply,
option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::RemoveSystemGrantedReqPermissions(const std::string& bundleName)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::REMOVE_SYSTEM_GRANTED_REQ_PERMISSIONS), data, reply,
option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::AddDefPermissions(const std::vector<PermissionDefParcel>& permDefList)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteInt32(permDefList.size())) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permDefList's size", __func__);
return RET_FAILED;
}
for (auto permissionDef : permDefList) {
if (!data.WriteParcelable(&permissionDef)) {
return RET_FAILED;
}
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::ADD_DEF_PERMISSIONS), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::RemoveDefPermissions(const std::string& bundleName)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write bundleName", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::REMOVE_DEF_PERMISSIONS), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
int PermissionManagerProxy::GetDefPermission(
const std::string& permissionName, PermissionDefParcel& permissionDefResult)
{
MessageParcel data;
data.WriteInterfaceToken(IPermissionManager::GetDescriptor());
if (!data.WriteString(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: Failed to write permissionName", __func__);
return RET_FAILED;
}
MessageParcel reply;
MessageOption option;
sptr<IRemoteObject> remote = Remote();
if (remote == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: remote service null.", __func__);
return RET_FAILED;
}
int32_t requestResult = remote->SendRequest(
static_cast<uint32_t>(IPermissionManager::InterfaceCode::GET_DEF_PERMISSION), data, reply, option);
if (requestResult != NO_ERROR) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s send request fail, result: %{public}d", __func__, requestResult);
return RET_FAILED;
}
sptr<PermissionDefParcel> resultSptr = reply.ReadParcelable<PermissionDefParcel>();
if (resultSptr == nullptr) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s ReadParcelable fail", __func__);
return RET_FAILED;
}
permissionDefResult = *resultSptr;
int32_t result = reply.ReadInt32();
PERMISSION_LOG_DEBUG(LABEL, "%{public}s get result from server data = %{public}d", __func__, result);
return result;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_MANAGER_PROXY_H
#define PERMISSION_MANAGER_PROXY_H
#include "i_permission_manager.h"
#include "iremote_proxy.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionManagerProxy : public IRemoteProxy<IPermissionManager> {
public:
explicit PermissionManagerProxy(const sptr<IRemoteObject>& impl);
virtual ~PermissionManagerProxy() override;
int VerifyPermission(const std::string& packageName, const std::string& permissionName, int userId) override;
bool CanRequestPermission(const std::string& bundleName, const std::string& permissionName, int userId) override;
int GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) override;
int GrantSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) override;
int RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) override;
int RevokeSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) override;
int AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId) override;
int AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList) override;
int RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId) override;
int RemoveSystemGrantedReqPermissions(const std::string& bundleName) override;
int AddDefPermissions(const std::vector<PermissionDefParcel>& permDefList) override;
int RemoveDefPermissions(const std::string& bundleName) override;
int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) override;
private:
static inline BrokerDelegator<PermissionManagerProxy> delegator_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_MANAGER_PROXY_H

View File

@ -0,0 +1,40 @@
# Copyright (C) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/test.gni")
ohos_unittest("libpermissionsdk_standard_test") {
subsystem_name = "security"
part_name = "permission_standard"
module_out_path = part_name + "/" + part_name
include_dirs = [
"//utils/native/base/include",
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission/",
]
sources = [ "unittest/cpp/src/permission_kit_test.cpp" ]
cflags_cc = [ "-DHILOG_ENABLE" ]
deps = [
"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx",
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard",
"//utils/native/base:utils",
]
}
group("unittest") {
testonly = true
deps = [ ":libpermissionsdk_standard_test" ]
}

View File

@ -0,0 +1,357 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_kit_test.h"
#include "test_const.h"
#include "permission_kit.h"
using namespace testing::ext;
using namespace OHOS::Security::Permission;
void PermissionKitTest::SetUpTestCase()
{}
void PermissionKitTest::TearDownTestCase()
{
PermissionKit::RemoveDefPermissions(TEST_BUNDLE_NAME);
PermissionKit::RemoveUserGrantedReqPermissions(TEST_BUNDLE_NAME, TEST_USER_ID);
PermissionKit::RemoveSystemGrantedReqPermissions(TEST_BUNDLE_NAME);
}
void PermissionKitTest::SetUp()
{
vector<PermissionDef> permDefList;
PermissionDef permissionDefAlpha = {
.permissionName = TEST_PERMISSION_NAME_ALPHA,
.bundleName = TEST_BUNDLE_NAME,
.grantMode = GrantMode::USER_GRANT,
.availableScope = AVAILABLE_SCOPE_ALL,
.label = TEST_LABEL,
.labelId = TEST_LABEL_ID,
.description = TEST_DESCRIPTION,
.descriptionId = TEST_DESCRIPTION_ID
};
PermissionDef permissionDefBeta = {
.permissionName = TEST_PERMISSION_NAME_BETA,
.bundleName = TEST_BUNDLE_NAME,
.grantMode = GrantMode::SYSTEM_GRANT,
.availableScope = AVAILABLE_SCOPE_ALL,
.label = TEST_LABEL,
.labelId = TEST_LABEL_ID,
.description = TEST_DESCRIPTION,
.descriptionId = TEST_DESCRIPTION_ID
};
permDefList.emplace_back(permissionDefAlpha);
permDefList.emplace_back(permissionDefBeta);
PermissionKit::AddDefPermissions(permDefList);
}
void PermissionKitTest::TearDown()
{}
/**
* @tc.name: AddDefPermissions001
* @tc.desc: Get permission definition info successfully after AddDefPermissions function has been invoked
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, AddDefPermissions001, TestSize.Level1)
{
PermissionDef permissionDefResultAlpha;
int ret = PermissionKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permissionDefResultAlpha);
ASSERT_EQ(RET_SUCCESS, ret);
PermissionDef permissionDefResultBeta;
ret = PermissionKit::GetDefPermission(TEST_PERMISSION_NAME_BETA, permissionDefResultBeta);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: RemoveDefPermissions001
* @tc.desc: Cannot get permission definition info after RemoveDefPermissions has been invoked
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, RemoveDefPermissions001, TestSize.Level1)
{
PermissionDef permissionDefResultAlpha;
int ret = PermissionKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, permissionDefResultAlpha);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::RemoveDefPermissions(TEST_BUNDLE_NAME);
ASSERT_EQ(RET_SUCCESS, ret);
PermissionDef result;
ret = PermissionKit::GetDefPermission(TEST_PERMISSION_NAME_ALPHA, result);
ASSERT_EQ(RET_FAILED, ret);
}
/**
* @tc.name: VerifyPermission001
* @tc.desc: Verify user granted permission
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermission001, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_ALPHA);
int ret = PermissionKit::AddUserGrantedReqPermissions(TEST_BUNDLE_NAME, permList, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::GrantUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_GRANTED, ret);
ret = PermissionKit::RevokeUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RemoveUserGrantedReqPermissions(TEST_BUNDLE_NAME, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: VerifyPermission002
* @tc.desc: Verify system granted permission
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermission002, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_BETA);
int ret = PermissionKit::AddSystemGrantedReqPermissions(TEST_BUNDLE_NAME, permList);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::GrantSystemGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_GRANTED, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_SUB_USER_ID);
ASSERT_EQ(PERMISSION_GRANTED, ret);
ret = PermissionKit::RevokeSystemGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_SUB_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RemoveSystemGrantedReqPermissions(TEST_BUNDLE_NAME);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: VerifyPermission003
* @tc.desc: Verify permission that has not been defined.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermission003, TestSize.Level1)
{
int ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_GAMMA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
}
/**
* @tc.name: VerifyPermissionErrorUserGrant001
* @tc.desc: Verify permission error that user granted but request system granted.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermissionErrorUserGrant001, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_ALPHA);
int ret = PermissionKit::AddSystemGrantedReqPermissions(TEST_BUNDLE_NAME, permList);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::GrantUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RevokeUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RemoveUserGrantedReqPermissions(TEST_BUNDLE_NAME, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: VerifyPermissionErrorUserGrant002
* @tc.desc: Verify permission error that user granted but grant system granted.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermissionErrorUserGrant002, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_ALPHA);
int ret = PermissionKit::AddUserGrantedReqPermissions(TEST_BUNDLE_NAME, permList, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::GrantSystemGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RevokeUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RemoveUserGrantedReqPermissions(TEST_BUNDLE_NAME, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: VerifyPermissionErrorSystemGrant001
* @tc.desc: Verify permission error that system granted but request user granted.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermissionErrorSystemGrant001, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_BETA);
int ret = PermissionKit::AddUserGrantedReqPermissions(TEST_BUNDLE_NAME, permList, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::GrantSystemGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RevokeSystemGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RemoveUserGrantedReqPermissions(TEST_BUNDLE_NAME, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: VerifyPermissionErrorSystemGrant002
* @tc.desc: Verify permission error that system granted but grant user granted.
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, VerifyPermissionErrorSystemGrant002, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_BETA);
int ret = PermissionKit::AddSystemGrantedReqPermissions(TEST_BUNDLE_NAME, permList);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::GrantUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_SUB_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RevokeSystemGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA);
ASSERT_EQ(RET_SUCCESS, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::VerifyPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_SUB_USER_ID);
ASSERT_EQ(PERMISSION_NOT_GRANTED, ret);
ret = PermissionKit::RemoveUserGrantedReqPermissions(TEST_BUNDLE_NAME, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
}
/**
* @tc.name: CanRequestPermission001
* @tc.desc: For user granted permission and permission is granted, can request permission
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, CanRequestPermission001, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_ALPHA);
int ret = PermissionKit::AddUserGrantedReqPermissions(TEST_BUNDLE_NAME, permList, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
bool isCanRequest = PermissionKit::CanRequestPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_TRUE(isCanRequest);
ret = PermissionKit::GrantUserGrantedPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_EQ(RET_SUCCESS, ret);
isCanRequest = PermissionKit::CanRequestPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_FALSE(isCanRequest);
ret = PermissionKit::RemoveDefPermissions(TEST_BUNDLE_NAME);
ASSERT_EQ(RET_SUCCESS, ret);
isCanRequest = PermissionKit::CanRequestPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_ALPHA, TEST_USER_ID);
ASSERT_FALSE(isCanRequest);
}
/**
* @tc.name: CanRequestPermission001
* @tc.desc: For non user granted permission, can not request permission
* @tc.type: FUNC
* @tc.require:
*/
HWTEST_F(PermissionKitTest, CanRequestPermission002, TestSize.Level1)
{
vector<string> permList;
permList.push_back(TEST_PERMISSION_NAME_BETA);
int ret = PermissionKit::AddSystemGrantedReqPermissions(TEST_BUNDLE_NAME, permList);
ASSERT_EQ(RET_SUCCESS, ret);
bool isCanRequest = PermissionKit::CanRequestPermission(TEST_BUNDLE_NAME, TEST_PERMISSION_NAME_BETA, TEST_USER_ID);
ASSERT_FALSE(isCanRequest);
isCanRequest = PermissionKit::CanRequestPermission("", "", TEST_INVALID_USER_ID);
ASSERT_FALSE(isCanRequest);
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_KIT_TEST_H
#define PERMISSION_KIT_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionKitTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp();
void TearDown();
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_KIT_TEST_H

0
interfaces/kits/permission_lite/BUILD.gn Normal file → Executable file
View File

0
interfaces/kits/permission_lite/pms_interface.h Normal file → Executable file
View File

View File

@ -0,0 +1,14 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos.gni")

30
ohos.build Executable file
View File

@ -0,0 +1,30 @@
{
"subsystem": "security",
"parts": {
"permission_standard": {
"variants": [
"phone",
"wearable"
],
"inner_kits": [
{
"name": "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk:libpermissionsdk_standard",
"header": {
"header_files": [
"permission/permission.h",
"permission/permission_def.h",
"permission/permission_kit.h"
],
"header_base": "//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include"
}
}
],
"module_list": [
"//base/security/permission:permission_build_module_standard"
],
"test_list": [
"//base/security/permission:permission_build_module_standard_test"
]
}
}
}

0
services/permission_lite/BUILD.gn Normal file → Executable file
View File

View File

0
services/permission_lite/ipc_auth/src/ipc_auth_impl.c Normal file → Executable file
View File

0
services/permission_lite/js_api/BUILD.gn Normal file → Executable file
View File

0
services/permission_lite/js_api/include/perm_module.h Normal file → Executable file
View File

0
services/permission_lite/js_api/src/perm_module.cpp Normal file → Executable file
View File

0
services/permission_lite/pms/BUILD.gn Normal file → Executable file
View File

0
services/permission_lite/pms/include/hals/hal_pms.h Normal file → Executable file
View File

0
services/permission_lite/pms/include/perm_define.h Normal file → Executable file
View File

0
services/permission_lite/pms/include/perm_operate.h Normal file → Executable file
View File

0
services/permission_lite/pms/include/pms.h Normal file → Executable file
View File

0
services/permission_lite/pms/include/pms_inner.h Normal file → Executable file
View File

0
services/permission_lite/pms/src/perm_operate.c Normal file → Executable file
View File

0
services/permission_lite/pms/src/pms_impl.c Normal file → Executable file
View File

0
services/permission_lite/pms/src/pms_inner.c Normal file → Executable file
View File

0
services/permission_lite/pms/src/pms_server.c Normal file → Executable file
View File

0
services/permission_lite/pms/src/pms_server_internal.c Normal file → Executable file
View File

0
services/permission_lite/pms_base/BUILD.gn Normal file → Executable file
View File

0
services/permission_lite/pms_base/include/pms_common.h Normal file → Executable file
View File

0
services/permission_lite/pms_client/BUILD.gn Normal file → Executable file
View File

0
services/permission_lite/pms_client/perm_client.c Normal file → Executable file
View File

View File

@ -0,0 +1,58 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos.gni")
ohos_shared_library("permission_manager_service_standard") {
subsystem_name = "security"
part_name = "permission_standard"
include_dirs = [
"include",
"//utils/system/safwk/native/include",
"//base/security/permission/frameworks/permission_standard/permissioninfrastructure",
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission",
]
sources = [
"main/cpp/src/data_storage.cpp",
"main/cpp/src/data_translator.cpp",
"main/cpp/src/generic_values.cpp",
"main/cpp/src/permission_definition_cache.cpp",
"main/cpp/src/permission_definition_manager.cpp",
"main/cpp/src/permission_manager_service.cpp",
"main/cpp/src/permission_manager_stub.cpp",
"main/cpp/src/permission_state_cache.cpp",
"main/cpp/src/permission_state_manager.cpp",
"main/cpp/src/sqlite_helper.cpp",
"main/cpp/src/sqlite_storage.cpp",
"main/cpp/src/statement.cpp",
"main/cpp/src/variant_value.cpp",
]
cflags_cc = [ "-DHILOG_ENABLE" ]
deps = [
"//base/security/permission/frameworks/permission_standard/permissioncommunicationadapter:permission_standard_communication_adapter_cxx",
"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx",
"//third_party/sqlite:sqlite",
"//utils/native/base:utils",
]
external_deps = [
"hiviewdfx_hilog_native:libhilog",
"ipc:ipc_core",
"safwk:system_ability_fwk",
"samgr_L2:samgr_proxy",
]
}

View File

@ -0,0 +1,29 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "data_storage.h"
#include "sqlite_storage.h"
namespace OHOS {
namespace Security {
namespace Permission {
DataStorage& DataStorage::GetRealDataStorage()
{
return SqliteStorage::GetInstance();
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,49 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef DATA_STORAGE_H
#define DATA_STORAGE_H
#include <vector>
#include <map>
#include "generic_values.h"
namespace OHOS {
namespace Security {
namespace Permission {
class DataStorage {
public:
enum DataType { PERMISSION_DEF, PERMISSIONS_STAT_USER_GRANTED, PERMISSIONS_STAT_SYSTEM_GRANTED };
static DataStorage& GetRealDataStorage();
virtual ~DataStorage() = default;
virtual int Add(const DataType type, const std::vector<GenericValues>& values) = 0;
virtual int Remove(const DataType type, const GenericValues& conditions) = 0;
virtual int Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) = 0;
virtual int Find(const DataType type, std::vector<GenericValues>& results) = 0;
virtual int RefreshAll(const DataType type, const std::vector<GenericValues>& values) = 0;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // DATA_STORAGE_H

View File

@ -0,0 +1,82 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "data_translator.h"
#include "permission.h"
#include "field_const.h"
namespace OHOS {
namespace Security {
namespace Permission {
int DataTranslator::TranslationIntoPermissionDef(const GenericValues& inGenericValues, PermissionDef& outPermissionDef)
{
outPermissionDef.permissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME);
outPermissionDef.bundleName = inGenericValues.GetString(FIELD_BUNDLE_NAME);
outPermissionDef.grantMode = inGenericValues.GetInt(FIELD_GRANT_MODE);
outPermissionDef.availableScope = inGenericValues.GetInt(FIELD_AVAILABLE_SCOPE);
outPermissionDef.label = inGenericValues.GetString(FIELD_LABEL);
outPermissionDef.labelId = inGenericValues.GetInt(FIELD_LABEL_ID);
outPermissionDef.description = inGenericValues.GetString(FIELD_DESCRIPTION);
outPermissionDef.descriptionId = inGenericValues.GetInt(FIELD_DESCRIPTION_ID);
return RET_SUCCESS;
}
int DataTranslator::TranslationIntoGenericValues(const PermissionDef& inPermissionDef, GenericValues& outGenericValues)
{
outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionDef.permissionName);
outGenericValues.Put(FIELD_BUNDLE_NAME, inPermissionDef.bundleName);
outGenericValues.Put(FIELD_GRANT_MODE, inPermissionDef.grantMode);
outGenericValues.Put(FIELD_AVAILABLE_SCOPE, inPermissionDef.availableScope);
outGenericValues.Put(FIELD_LABEL, inPermissionDef.label);
outGenericValues.Put(FIELD_LABEL_ID, inPermissionDef.labelId);
outGenericValues.Put(FIELD_DESCRIPTION, inPermissionDef.description);
outGenericValues.Put(FIELD_DESCRIPTION_ID, inPermissionDef.descriptionId);
return RET_SUCCESS;
}
int DataTranslator::TranslationIntoPermissionReq(const GenericValues& inGenericValues, PermissionReq& outPermissionReq)
{
outPermissionReq.reqPermissionName = inGenericValues.GetString(FIELD_PERMISSION_NAME);
outPermissionReq.isGranted = inGenericValues.GetInt(FIELD_GRANTED) != 0;
outPermissionReq.flags = inGenericValues.GetInt(FIELD_FLAGS);
return RET_SUCCESS;
}
int DataTranslator::TranslationIntoGenericValues(const PermissionReq& inPermissionReq, GenericValues& outGenericValues)
{
outGenericValues.Put(FIELD_PERMISSION_NAME, inPermissionReq.reqPermissionName);
outGenericValues.Put(FIELD_GRANTED, inPermissionReq.isGranted ? 1 : 0);
outGenericValues.Put(FIELD_FLAGS, inPermissionReq.flags);
return RET_SUCCESS;
}
std::string DataTranslator::ToString(const PermissionDef& inPermissionDef)
{
std::string infos;
infos.append(R"({"permissionName": ")" + inPermissionDef.permissionName + R"(")");
infos.append(R"(, "bundleName": ")" + inPermissionDef.bundleName + R"(")");
infos.append(R"(, "grantMode": )" + std::to_string(inPermissionDef.grantMode));
infos.append(R"(, "availableScope": )" + std::to_string(inPermissionDef.availableScope));
infos.append(R"(, "label": ")" + inPermissionDef.label + R"(")");
infos.append(R"(, "labelId": )" + std::to_string(inPermissionDef.labelId));
infos.append(R"(, "description": ")" + inPermissionDef.description + R"(")");
infos.append(R"(, "descriptionId": )" + std::to_string(inPermissionDef.descriptionId));
infos.append("}");
return infos;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,39 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef DATA_TRANSLATOR_H
#define DATA_TRANSLATOR_H
#include <string>
#include "permission_def.h"
#include "permission_req.h"
#include "generic_values.h"
namespace OHOS {
namespace Security {
namespace Permission {
class DataTranslator final {
public:
static int TranslationIntoPermissionDef(const GenericValues& inGenericValues, PermissionDef& outPermissionDef);
static int TranslationIntoPermissionReq(const GenericValues& inGenericValues, PermissionReq& outPermissionReq);
static int TranslationIntoGenericValues(const PermissionDef& inPermissionDef, GenericValues& outGenericValues);
static int TranslationIntoGenericValues(const PermissionReq& inPermissionReq, GenericValues& outGenericValues);
static std::string ToString(const PermissionDef& inPermissionDef);
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // DATA_TRANSLATOR_H

View File

@ -0,0 +1,38 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef FIELD_CONST_H
#define FIELD_CONST_H
#include <string>
namespace OHOS {
namespace Security {
namespace Permission {
const std::string FIELD_PERMISSION_NAME = "permission_name";
const std::string FIELD_BUNDLE_NAME = "bundle_name";
const std::string FIELD_GRANT_MODE = "grant_mode";
const std::string FIELD_AVAILABLE_SCOPE = "available_scope";
const std::string FIELD_LABEL = "label";
const std::string FIELD_LABEL_ID = "label_id";
const std::string FIELD_DESCRIPTION = "description";
const std::string FIELD_DESCRIPTION_ID = "description_id";
const std::string FIELD_USER_ID = "user_id";
const std::string FIELD_GRANTED = "granted";
const std::string FIELD_FLAGS = "flags";
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // FIELD_CONST_H

View File

@ -0,0 +1,73 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "generic_values.h"
namespace OHOS {
namespace Security {
namespace Permission {
void GenericValues::Put(const std::string& key, int value)
{
map_.insert(std::make_pair(key, VariantValue(value)));
}
void GenericValues::Put(const std::string& key, const std::string& value)
{
map_.insert(std::make_pair(key, VariantValue(value)));
}
void GenericValues::Put(const std::string& key, const VariantValue& value)
{
map_.insert(std::make_pair(key, value));
}
VariantValue GenericValues::Get(const std::string& key) const
{
auto iter = map_.find(key);
if (iter == map_.end()) {
return VariantValue();
}
return iter->second;
}
int GenericValues::GetInt(const std::string& key) const
{
auto it = map_.find(key);
if (it == map_.end()) {
return VariantValue::DEFAULT_VALUE;
}
return it->second.GetInt();
}
std::string GenericValues::GetString(const std::string& key) const
{
auto it = map_.find(key);
if (it == map_.end()) {
return std::string();
}
return it->second.GetString();
}
std::vector<std::string> GenericValues::GetAllKeys() const
{
std::vector<std::string> keys;
for (auto it = map_.begin(); it != map_.end(); ++it) {
keys.emplace_back(it->first);
}
return keys;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,53 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef GENERIC_VALUES_H
#define GENERIC_VALUES_H
#include <map>
#include <vector>
#include <string>
#include "variant_value.h"
namespace OHOS {
namespace Security {
namespace Permission {
class GenericValues final {
public:
GenericValues() = default;
virtual ~GenericValues() = default;
void Put(const std::string& key, int value);
void Put(const std::string& key, const std::string& value);
void Put(const std::string& key, const VariantValue& value);
std::vector<std::string> GetAllKeys() const;
VariantValue Get(const std::string& key) const;
int GetInt(const std::string& key) const;
std::string GetString(const std::string& key) const;
private:
std::map<std::string, VariantValue> map_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // GENERIC_VALUES_H

View File

@ -0,0 +1,133 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_definition_cache.h"
#include "permission.h"
#include "data_translator.h"
#include "permission_log.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionDefinitionCache"
};
}
PermissionDefinitionCache& PermissionDefinitionCache::GetInstance()
{
static PermissionDefinitionCache instance;
return instance;
}
PermissionDefinitionCache::PermissionDefinitionCache()
{}
PermissionDefinitionCache::~PermissionDefinitionCache()
{}
bool PermissionDefinitionCache::Insert(const PermissionDef& info)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
auto it = permissionDefinitionMap_.find(info.permissionName);
if (it != permissionDefinitionMap_.end()) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: info for permission: %{public}s has been insert, please check!",
__func__, info.permissionName.c_str());
return false;
}
permissionDefinitionMap_[info.permissionName] = info;
return true;
}
void PermissionDefinitionCache::DeleteByBundleName(const std::string& bundleName)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
auto it = permissionDefinitionMap_.begin();
while (it != permissionDefinitionMap_.end()) {
if (bundleName == it->second.bundleName) {
permissionDefinitionMap_.erase(it++);
} else {
++it;
}
}
}
int PermissionDefinitionCache::FindByPermissionName(const std::string& permissionName, PermissionDef& info)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
auto it = permissionDefinitionMap_.find(permissionName);
if (it == permissionDefinitionMap_.end()) {
PERMISSION_LOG_DEBUG(LABEL, "%{public}s: can not find definition info for permission: %{public}s", __func__,
permissionName.c_str());
return RET_FAILED;
}
info = it->second;
return RET_SUCCESS;
}
bool PermissionDefinitionCache::IsSystemGrantedPermission(const std::string& permissionName)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
return IsGrantedModeEqualInner(permissionName, SYSTEM_GRANT);
}
bool PermissionDefinitionCache::IsUserGrantedPermission(const std::string& permissionName)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
return IsGrantedModeEqualInner(permissionName, USER_GRANT);
}
std::string PermissionDefinitionCache::ToString()
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
std::string infos = R"({"Cache": "Default", "DefPermissions": [)";
for (const auto& request : permissionDefinitionMap_) {
PermissionDef permissionDef = request.second;
infos.append(DataTranslator::ToString(request.second));
infos.append(", ");
}
infos = infos + "]}";
return infos;
}
bool PermissionDefinitionCache::IsGrantedModeEqualInner(const std::string& permissionName, int grantMode) const
{
auto it = permissionDefinitionMap_.find(permissionName);
if (it == permissionDefinitionMap_.end()) {
return false;
}
return it->second.grantMode == grantMode;
}
bool PermissionDefinitionCache::HasDefinition(const std::string& permissionName)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
return permissionDefinitionMap_.count(permissionName) == 1;
}
void PermissionDefinitionCache::QueryCurrentCache(std::vector<GenericValues>& valueList)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
for (auto it = permissionDefinitionMap_.begin(); it != permissionDefinitionMap_.end(); ++it) {
GenericValues genericValues;
DataTranslator::TranslationIntoGenericValues(it->second, genericValues);
valueList.emplace_back(genericValues);
}
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,71 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_DEFINITION_CACHE_H
#define PERMISSION_DEFINITION_CACHE_H
#include <map>
#include <vector>
#include "permission_def.h"
#include "generic_values.h"
#include "rwlock.h"
#include "nocopyable.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionDefinitionCache final {
public:
static PermissionDefinitionCache& GetInstance();
virtual ~PermissionDefinitionCache();
bool Insert(const PermissionDef& info);
void DeleteByBundleName(const std::string& bundleName);
int FindByPermissionName(const std::string& permissionName, PermissionDef& info);
bool IsSystemGrantedPermission(const std::string& permissionName);
bool IsUserGrantedPermission(const std::string& permissionName);
bool HasDefinition(const std::string& permissionName);
void QueryCurrentCache(std::vector<GenericValues>& valueList);
std::string ToString();
private:
PermissionDefinitionCache();
bool IsGrantedModeEqualInner(const std::string& permissionName, int grantMode) const;
DISALLOW_COPY_AND_MOVE(PermissionDefinitionCache);
/**
* key: permission name.
* value: PermissionDef.
*/
std::map<std::string, PermissionDef> permissionDefinitionMap_;
OHOS::Utils::RWLock cacheLock_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_DEFINITION_CACHE_H

View File

@ -0,0 +1,152 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_definition_manager.h"
#include "permission_definition_cache.h"
#include "data_storage.h"
#include "data_translator.h"
#include "permission_log.h"
#include "permission.h"
#include "data_validator.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {
LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionDefinitionManager"
};
}
PermissionDefinitionManager& PermissionDefinitionManager::GetInstance()
{
static PermissionDefinitionManager instance;
return instance;
}
PermissionDefinitionManager::PermissionDefinitionManager() : hasInited_(false)
{}
PermissionDefinitionManager::~PermissionDefinitionManager()
{
if (!hasInited_) {
return;
}
this->permissionDefDataAccessWorker_.Stop();
this->hasInited_ = false;
}
void PermissionDefinitionManager::Init()
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->rwLock_);
if (hasInited_) {
return;
}
PERMISSION_LOG_INFO(LABEL, "init begin!");
std::vector<GenericValues> results;
DataStorage::GetRealDataStorage().Find(DataStorage::PERMISSION_DEF, results);
for (auto value : results) {
PermissionDef permissionDef;
DataTranslator::TranslationIntoPermissionDef(value, permissionDef);
PermissionDefinitionCache::GetInstance().Insert(permissionDef);
}
this->permissionDefDataAccessWorker_.Start(1);
hasInited_ = true;
PERMISSION_LOG_INFO(LABEL, "Init success");
}
void PermissionDefinitionManager::AddDefPermissions(const std::vector<PermissionDefParcel>& permList)
{
if (permList.empty()) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
for (const auto& permissionDefParcel : permList) {
if (!IsPermissionDefValid(permissionDefParcel.permissionDef)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid permission definition info: %{public}s", __func__,
DataTranslator::ToString(permissionDefParcel.permissionDef).c_str());
continue;
}
PermissionDefinitionCache::GetInstance().Insert(permissionDefParcel.permissionDef);
}
RefreshPersistentDataIfNeeded();
}
void PermissionDefinitionManager::RemoveDefPermissions(const std::string& bundleName)
{
if (!DataValidator::IsBundleNameValid(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionDefinitionCache::GetInstance().DeleteByBundleName(bundleName);
RefreshPersistentDataIfNeeded();
}
int PermissionDefinitionManager::GetDefPermission(
const std::string& permissionName, PermissionDefParcel& permissionDefParcel) const
{
if (!DataValidator::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return RET_FAILED;
}
return PermissionDefinitionCache::GetInstance().FindByPermissionName(
permissionName, permissionDefParcel.permissionDef);
}
bool PermissionDefinitionManager::IsGrantModeValid(const int grantMode) const
{
return grantMode == GrantMode::SYSTEM_GRANT || grantMode == GrantMode::USER_GRANT;
}
bool PermissionDefinitionManager::IsAvailableScopeValid(const int availableScope) const
{
return availableScope == AvailableScope::AVAILABLE_SCOPE_ALL ||
availableScope == AvailableScope::AVAILABLE_SCOPE_RESTRICTED ||
availableScope == AvailableScope::AVAILABLE_SCOPE_SIGNATURE;
}
bool PermissionDefinitionManager::IsPermissionDefValid(const PermissionDef& permissionDef) const
{
if (!DataValidator::IsPermissionNameValid(permissionDef.permissionName)) {
return false;
}
if (!DataValidator::IsBundleNameValid(permissionDef.bundleName)) {
return false;
}
if (!IsGrantModeValid(permissionDef.grantMode)) {
return false;
}
return IsAvailableScopeValid(permissionDef.availableScope);
}
void PermissionDefinitionManager::RefreshPersistentDataIfNeeded()
{
if (permissionDefDataAccessWorker_.GetCurTaskNum() > 1) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: has refresh task!", __func__);
return;
}
permissionDefDataAccessWorker_.AddTask([]() {
std::vector<GenericValues> valueList;
PermissionDefinitionCache::GetInstance().QueryCurrentCache(valueList);
DataStorage::GetRealDataStorage().RefreshAll(DataStorage::PERMISSION_DEF, valueList);
// Sleep for one second to avoid frequent refresh of the database.
std::this_thread::sleep_for(std::chrono::seconds(1));
});
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,67 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_DEFINITION_MANAGER_H
#define PERMISSION_DEFINITION_MANAGER_H
#include <vector>
#include "permission_def_parcel.h"
#include "field_const.h"
#include "nocopyable.h"
#include "thread_pool.h"
#include "rwlock.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionDefinitionManager final {
public:
static PermissionDefinitionManager& GetInstance();
void Init();
virtual ~PermissionDefinitionManager();
void AddDefPermissions(const std::vector<PermissionDefParcel>& permList);
void RemoveDefPermissions(const std::string& bundleName);
int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefParcel) const;
private:
PermissionDefinitionManager();
DISALLOW_COPY_AND_MOVE(PermissionDefinitionManager);
bool IsGrantModeValid(const int grantMode) const;
bool IsAvailableScopeValid(const int availableScope) const;
bool IsPermissionDefValid(const PermissionDef& permissionDef) const;
void RefreshPersistentDataIfNeeded();
OHOS::ThreadPool permissionDefDataAccessWorker_;
bool hasInited_;
OHOS::Utils::RWLock rwLock_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_DEFINITION_MANAGER_H

View File

@ -0,0 +1,189 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_manager_service.h"
#include "permission.h"
#include "permission_definition_manager.h"
#include "permission_state_manager.h"
#include "permission_log.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionManagerService"};
}
const bool REGISTER_RESULT =
SystemAbility::MakeAndRegisterAbility(DelayedSingleton<PermissionManagerService>::GetInstance().get());
PermissionManagerService::PermissionManagerService()
: SystemAbility(SA_ID_PERMISSION_MANAGER_SERVICE, true), state_(ServiceRunningState::STATE_NOT_START)
{
PERMISSION_LOG_INFO(LABEL, "PermissionManagerService()");
}
PermissionManagerService::~PermissionManagerService()
{
PERMISSION_LOG_INFO(LABEL, "~PermissionManagerService()");
}
void PermissionManagerService::OnStart()
{
if (state_ == ServiceRunningState::STATE_RUNNING) {
PERMISSION_LOG_INFO(LABEL, "PermissionManagerService has already started!");
return;
}
PERMISSION_LOG_INFO(LABEL, "PermissionManagerService is starting");
if (!Initialize()) {
PERMISSION_LOG_ERROR(LABEL, "Failed to initialize");
return;
}
state_ = ServiceRunningState::STATE_RUNNING;
bool ret = Publish(DelayedSingleton<PermissionManagerService>::GetInstance().get());
if (!ret) {
PERMISSION_LOG_ERROR(LABEL, "Failed to publish service!");
return;
}
PERMISSION_LOG_INFO(LABEL, "Congratulations, PermissionManagerService start successfully!");
}
void PermissionManagerService::OnStop()
{
PERMISSION_LOG_INFO(LABEL, "stop service");
state_ = ServiceRunningState::STATE_NOT_START;
}
int PermissionManagerService::VerifyPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL,
"%{public}s called, packageName: %{public}s, permissionName: %{public}s, userId: %{public}d", __func__,
bundleName.c_str(), permissionName.c_str(), userId);
return PermissionStateManager::GetInstance().VerifyPermission(bundleName, permissionName, userId);
}
bool PermissionManagerService::CanRequestPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL,
"%{public}s called, bundleName: %{public}s, permissionName: %{public}s, userId: %{public}d", __func__,
bundleName.c_str(), permissionName.c_str(), userId);
return PermissionStateManager::GetInstance().CanRequestPermission(bundleName, permissionName, userId);
}
int PermissionManagerService::GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL,
"%{public}s called, bundleName: %{public}s, permissionName: %{public}s, userId: %{public}d", __func__,
bundleName.c_str(), permissionName.c_str(), userId);
PermissionStateManager::GetInstance().GrantUserGrantedPermission(bundleName, permissionName, userId);
return RET_SUCCESS;
}
int PermissionManagerService::GrantSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, bundleName: %{public}s, permissionName: %{public}s", __func__,
bundleName.c_str(), permissionName.c_str());
PermissionStateManager::GetInstance().GrantSystemGrantedPermission(bundleName, permissionName);
return RET_SUCCESS;
}
int PermissionManagerService::RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
PERMISSION_LOG_INFO(LABEL,
"%{public}s called, bundleName: %{public}s, permissionName: %{public}s, userId: %{public}d", __func__,
bundleName.c_str(), permissionName.c_str(), userId);
PermissionStateManager::GetInstance().RevokeUserGrantedPermission(bundleName, permissionName, userId);
return RET_SUCCESS;
}
int PermissionManagerService::RevokeSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, bundleName: %{public}s, permissionName: %{public}s", __func__,
bundleName.c_str(), permissionName.c_str());
PermissionStateManager::GetInstance().RevokeSystemGrantedPermission(bundleName, permissionName);
return RET_SUCCESS;
}
int PermissionManagerService::AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId)
{
PERMISSION_LOG_INFO(LABEL,
"%{public}s called, bundleName: %{public}s, permList size: %{public}d, userId: %{public}d", __func__,
bundleName.c_str(), (int) permList.size(), userId);
PermissionStateManager::GetInstance().AddUserGrantedReqPermissions(bundleName, permList, userId);
return RET_SUCCESS;
}
int PermissionManagerService::AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, bundleName: %{public}s, permList size: %{public}d", __func__,
bundleName.c_str(), (int) permList.size());
PermissionStateManager::GetInstance().AddSystemGrantedReqPermissions(bundleName, permList);
return RET_SUCCESS;
}
int PermissionManagerService::RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId)
{
PERMISSION_LOG_INFO(
LABEL, "%{public}s called, bundleName: %{public}s, userId: %{public}d", __func__, bundleName.c_str(), userId);
PermissionStateManager::GetInstance().RemoveUserGrantedReqPermissions(bundleName, userId);
return RET_SUCCESS;
}
int PermissionManagerService::RemoveSystemGrantedReqPermissions(const std::string& bundleName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, bundleName: %{public}s", __func__, bundleName.c_str());
PermissionStateManager::GetInstance().RemoveSystemGrantedReqPermissions(bundleName);
return RET_SUCCESS;
}
int PermissionManagerService::AddDefPermissions(const std::vector<PermissionDefParcel>& permDefList)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) permDefList.size());
PermissionDefinitionManager::GetInstance().AddDefPermissions(permDefList);
return RET_SUCCESS;
}
int PermissionManagerService::RemoveDefPermissions(const std::string& bundleName)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, bundleName: %{public}s", __func__, bundleName.c_str());
PermissionDefinitionManager::GetInstance().RemoveDefPermissions(bundleName);
return RET_SUCCESS;
}
int PermissionManagerService::GetDefPermission(
const std::string& permissionName, PermissionDefParcel& permissionDefResult)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, bundleName: %{public}s", __func__, permissionName.c_str());
return PermissionDefinitionManager::GetInstance().GetDefPermission(permissionName, permissionDefResult);
}
bool PermissionManagerService::Initialize() const
{
PermissionDefinitionManager::GetInstance().Init();
PermissionStateManager::GetInstance().Init();
return true;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,76 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_MANAGER_SERVICE_H
#define PERMISSION_MANAGER_SERVICE_H
#include "permission_manager_stub.h"
#include "singleton.h"
#include "iremote_object.h"
#include "system_ability.h"
#include "nocopyable.h"
namespace OHOS {
namespace Security {
namespace Permission {
enum class ServiceRunningState { STATE_NOT_START, STATE_RUNNING };
class PermissionManagerService final : public SystemAbility, public PermissionManagerStub {
DECLARE_DELAYED_SINGLETON(PermissionManagerService);
DECLEAR_SYSTEM_ABILITY(PermissionManagerService);
public:
void OnStart() override;
void OnStop() override;
int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) override;
bool CanRequestPermission(const std::string& bundleName, const std::string& permissionName, int userId) override;
int GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) override;
int GrantSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) override;
int RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId) override;
int RevokeSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName) override;
int AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId) override;
int AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList) override;
int RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId) override;
int RemoveSystemGrantedReqPermissions(const std::string& bundleName) override;
int AddDefPermissions(const std::vector<PermissionDefParcel>& permDefList) override;
int RemoveDefPermissions(const std::string& bundleName) override;
int GetDefPermission(const std::string& permissionName, PermissionDefParcel& permissionDefResult) override;
private:
bool Initialize() const;
ServiceRunningState state_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_MANAGER_SERVICE_H

View File

@ -0,0 +1,266 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_manager_stub.h"
#include "permission.h"
#include "permission_log.h"
#include "ipc_skeleton.h"
#include "string_ex.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionManagerStub"};
}
int32_t PermissionManagerStub::OnRemoteRequest(
uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& option)
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called, code: %{public}d", __func__, code);
std::u16string descriptor = data.ReadInterfaceToken();
if (descriptor != IPermissionManager::GetDescriptor()) {
PERMISSION_LOG_ERROR(LABEL, "get unexpect descriptor: %{public}s", Str16ToStr8(descriptor).c_str());
return RET_FAILED;
}
switch (code) {
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::VERIFY_PERMISSION):
VerifyPermissionInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::CAN_REQUEST_PERMISSION):
CanRequestPermissionInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::GRANT_USER_GRANTED_PERMISSION):
GrantUserGrantedPermissionInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::GRANT_SYSTEM_GRANTED_PERMISSION):
GrantSystemGrantedPermissionInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::REVOKE_USER_GRANTED_PERMISSION):
RevokeUserGrantedPermissionInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::REVOKE_SYSTEM_GRANTED_PERMISSION):
RevokeSystemGrantedPermissionInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::ADD_USER_GRANTED_REQ_PERMISSIONS):
AddUserGrantedReqPermissionsInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::ADD_SYSTEM_GRANTED_REQ_PERMISSIONS):
AddSystemGrantedReqPermissionsInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::REMOVE_USER_GRANTED_REQ_PERMISSIONS):
RemoveUserGrantedReqPermissionsInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::REMOVE_SYSTEM_GRANTED_REQ_PERMISSIONS):
RemoveSystemGrantedReqPermissionsInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::ADD_DEF_PERMISSIONS):
AddDefPermissionsInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::REMOVE_DEF_PERMISSIONS):
RemoveDefPermissionsInner(data, reply);
break;
case static_cast<uint32_t>(IPermissionManager::InterfaceCode::GET_DEF_PERMISSION):
GetDefPermissionInner(data, reply);
break;
default:
return IPCObjectStub::OnRemoteRequest(code, data, reply, option);
}
return NO_ERROR;
}
void PermissionManagerStub::VerifyPermissionInner(MessageParcel& data, MessageParcel& reply)
{
std::string bundleName = data.ReadString();
std::string permissionName = data.ReadString();
int userId = data.ReadInt32();
int result = this->VerifyPermission(bundleName, permissionName, userId);
reply.WriteInt32(result);
}
void PermissionManagerStub::CanRequestPermissionInner(MessageParcel& data, MessageParcel& reply)
{
std::string bundleName = data.ReadString();
std::string permissionName = data.ReadString();
int userId = data.ReadInt32();
int result = this->CanRequestPermission(bundleName, permissionName, userId);
reply.WriteBool(result);
}
void PermissionManagerStub::GrantUserGrantedPermissionInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
std::string permissionName = data.ReadString();
int userId = data.ReadInt32();
int result = this->GrantUserGrantedPermission(bundleName, permissionName, userId);
reply.WriteInt32(result);
}
void PermissionManagerStub::GrantSystemGrantedPermissionInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
std::string permissionName = data.ReadString();
int result = this->GrantSystemGrantedPermission(bundleName, permissionName);
reply.WriteInt32(result);
}
void PermissionManagerStub::RevokeUserGrantedPermissionInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
std::string permissionName = data.ReadString();
int userId = data.ReadInt32();
int result = this->RevokeUserGrantedPermission(bundleName, permissionName, userId);
reply.WriteInt32(result);
}
void PermissionManagerStub::RevokeSystemGrantedPermissionInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
std::string permissionName = data.ReadString();
int result = this->RevokeSystemGrantedPermission(bundleName, permissionName);
reply.WriteInt32(result);
}
void PermissionManagerStub::AddUserGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
std::vector<std::string> permList;
data.ReadStringVector(&permList);
int userId = data.ReadInt32();
int result = this->AddUserGrantedReqPermissions(bundleName, permList, userId);
reply.WriteInt32(result);
}
void PermissionManagerStub::AddSystemGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
std::vector<std::string> permList;
data.ReadStringVector(&permList);
int result = this->AddSystemGrantedReqPermissions(bundleName, permList);
reply.WriteInt32(result);
}
void PermissionManagerStub::RemoveUserGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
int userId = data.ReadInt32();
int result = this->RemoveUserGrantedReqPermissions(bundleName, userId);
reply.WriteInt32(result);
}
void PermissionManagerStub::RemoveSystemGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
int result = this->RemoveSystemGrantedReqPermissions(bundleName);
reply.WriteInt32(result);
}
void PermissionManagerStub::AddDefPermissionsInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
int size = 0;
data.ReadInt32(size);
std::vector<PermissionDefParcel> permList;
for (int i = 0; i < size; i++) {
sptr<PermissionDefParcel> permissionDef = data.ReadParcelable<PermissionDefParcel>();
if (permissionDef != nullptr) {
permList.emplace_back(*permissionDef);
}
}
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permList size: %{public}d", __func__, (int) permList.size());
int result = this->AddDefPermissions(permList);
reply.WriteInt32(result);
}
void PermissionManagerStub::RemoveDefPermissionsInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
reply.WriteInt32(RET_FAILED);
return;
}
std::string bundleName = data.ReadString();
int result = this->RemoveDefPermissions(bundleName);
reply.WriteInt32(result);
}
void PermissionManagerStub::GetDefPermissionInner(MessageParcel& data, MessageParcel& reply)
{
if (!IsAuthorizedCalling()) {
PERMISSION_LOG_INFO(LABEL, "%{public}s called, permission denied", __func__);
return;
}
std::string permissionName = data.ReadString();
PermissionDefParcel permissionDefParcel;
int result = this->GetDefPermission(permissionName, permissionDefParcel);
reply.WriteParcelable(&permissionDefParcel);
reply.WriteInt32(result);
}
bool PermissionManagerStub::IsAuthorizedCalling() const
{
int callingUid = IPCSkeleton::GetCallingUid();
PERMISSION_LOG_INFO(LABEL, "Calling uid: %{public}d", callingUid);
return callingUid == SYSTEM_UID || callingUid == ROOT_UID;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,56 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_MANAGER_STUB_H
#define PERMISSION_MANAGER_STUB_H
#include "i_permission_manager.h"
#include "iremote_stub.h"
#include "nocopyable.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionManagerStub : public IRemoteStub<IPermissionManager> {
public:
PermissionManagerStub() = default;
virtual ~PermissionManagerStub() = default;
int OnRemoteRequest(uint32_t code, MessageParcel& data, MessageParcel& reply, MessageOption& options) override;
private:
void VerifyPermissionInner(MessageParcel& data, MessageParcel& reply);
void CanRequestPermissionInner(MessageParcel& data, MessageParcel& reply);
void GrantUserGrantedPermissionInner(MessageParcel& data, MessageParcel& reply);
void GrantSystemGrantedPermissionInner(MessageParcel& data, MessageParcel& reply);
void RevokeUserGrantedPermissionInner(MessageParcel& data, MessageParcel& reply);
void RevokeSystemGrantedPermissionInner(MessageParcel& data, MessageParcel& reply);
void AddUserGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply);
void AddSystemGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply);
void RemoveUserGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply);
void RemoveSystemGrantedReqPermissionsInner(MessageParcel& data, MessageParcel& reply);
void AddDefPermissionsInner(MessageParcel& data, MessageParcel& reply);
void RemoveDefPermissionsInner(MessageParcel& data, MessageParcel& reply);
void GetDefPermissionInner(MessageParcel& data, MessageParcel& reply);
bool IsAuthorizedCalling() const;
static const int SYSTEM_UID = 1000;
static const int ROOT_UID = 0;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_MANAGER_STUB_H

View File

@ -0,0 +1,33 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_STANDARD__PERMISSION_REQ_H
#define PERMISSION_STANDARD__PERMISSION_REQ_H
#include <string>
namespace OHOS {
namespace Security {
namespace Permission {
struct PermissionReq {
std::string reqPermissionName;
bool isGranted;
int flags;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_STANDARD__PERMISSION_REQ_H

View File

@ -0,0 +1,378 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_state_cache.h"
#include <iostream>
#include "permission.h"
#include "permission_log.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionStateCache"};
}
int PermissionStateCache::AddReqPermission(
const int userId, const std::string& bundleName, const std::string& permissionName)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
BundleInfo& bundleInfo = Root::GetRoot().GetOrCreateUserInfo(userId).GetOrCreateBundleInfo(bundleName);
return bundleInfo.AddReqPermission(permissionName);
}
int PermissionStateCache::AddReqPermission(
const int userId, const std::string& bundleName, const std::vector<std::string>& permList)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
BundleInfo& bundleInfo = Root::GetRoot().GetOrCreateUserInfo(userId).GetOrCreateBundleInfo(bundleName);
for (const auto& permissionName : permList) {
bundleInfo.AddReqPermission(permissionName);
}
return RET_SUCCESS;
}
int PermissionStateCache::ReplaceReqPermission(
int userId, const std::string& bundleName, const PermissionReq& permissionReq)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
return Root::GetRoot().GetOrCreateUserInfo(userId).ReplaceReqPermission(bundleName, permissionReq);
}
int PermissionStateCache::RemoveReqPermission(const int userId, const std::string& bundleName)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
if (!Root::GetRoot().HasUserInfo(userId)) {
return RET_FAILED;
}
return Root::GetRoot().GetOrCreateUserInfo(userId).RemoveReqPermission(bundleName);
}
int PermissionStateCache::UpdatePermissionState(
int userId, const std::string& bundleName, const std::string& permissionName, bool isGranted)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
if (!Root::GetRoot().HasUserInfo(userId)) {
return RET_FAILED;
}
return Root::GetRoot().GetOrCreateUserInfo(userId).UpdatePermissionState(bundleName, permissionName, isGranted);
}
int PermissionStateCache::UpdatePermissionFlags(
int userId, const std::string& bundleName, const std::string& permissionName, int flags)
{
Utils::UniqueWriteGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
if (!Root::GetRoot().HasUserInfo(userId)) {
return RET_FAILED;
}
return Root::GetRoot().GetOrCreateUserInfo(userId).UpdatePermissionFlags(bundleName, permissionName, flags);
}
bool PermissionStateCache::IsGranted(const int userId, const std::string& bundleName, const std::string& permissionName)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
if (!Root::GetRoot().HasUserInfo(userId)) {
return false;
}
return Root::GetRoot().GetOrCreateUserInfo(userId).IsGranted(bundleName, permissionName);
}
int PermissionStateCache::GetPermissionFlags(
const int userId, const std::string& bundleName, const std::string& permissionName)
{
if (!Root::GetRoot().HasUserInfo(userId)) {
return DEFAULT_PERMISSION_FLAGS;
}
return Root::GetRoot().GetOrCreateUserInfo(userId).GetPermissionFlags(bundleName, permissionName);
}
std::string PermissionStateCache::ToString()
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
return Root::GetRoot().ToString();
}
void PermissionStateCache::QueryCurrentCache(bool isSystemGranted, std::vector<GenericValues>& valueList)
{
Utils::UniqueReadGuard<Utils::RWLock> cacheGuard(this->cacheLock_);
if (isSystemGranted) {
if (!Root::GetRoot().HasUserInfo(SYSTEM_GRANTED_USER_ID)) {
return;
}
UserInfo userInfo = Root::GetRoot().GetOrCreateUserInfo(SYSTEM_GRANTED_USER_ID);
QueryForUser(userInfo, valueList);
return;
}
std::vector<UserInfo> userInfoList;
Root::GetRoot().GetUserGrantedUserInfo(userInfoList);
for (auto userInfo : userInfoList) {
QueryForUser(userInfo, valueList);
}
}
void PermissionStateCache::QueryForUser(const UserInfo& userInfo, std::vector<GenericValues>& valueList) const
{
std::vector<BundleInfo> bundleInfoList;
userInfo.GetAllBundleInfo(bundleInfoList);
for (auto bundleInfo : bundleInfoList) {
QueryForBundle(userInfo.userId_, bundleInfo, valueList);
}
}
void PermissionStateCache::QueryForBundle(
const int userId, const BundleInfo& bundleInfo, std::vector<GenericValues>& valueList) const
{
std::vector<PermissionReq> permissionReqList;
bundleInfo.GetAllPermissionReq(permissionReqList);
for (auto permissionReq : permissionReqList) {
GenericValues genericValues;
genericValues.Put(FIELD_BUNDLE_NAME, bundleInfo.bundleName_);
DataTranslator::TranslationIntoGenericValues(permissionReq, genericValues);
if (userId == SYSTEM_GRANTED_USER_ID) {
valueList.emplace_back(genericValues);
} else {
genericValues.Put(FIELD_USER_ID, userId);
valueList.emplace_back(genericValues);
}
}
}
PermissionStateCache& PermissionStateCache::GetInstance()
{
static PermissionStateCache instance;
return instance;
}
Root& Root::GetRoot()
{
static Root root;
return root;
}
bool Root::HasUserInfo(int userId) const
{
return userInfos_.count(userId) == 1;
}
UserInfo& Root::GetOrCreateUserInfo(const int userId)
{
if (!HasUserInfo(userId)) {
UserInfo userInfo(userId);
userInfos_[userId] = userInfo;
PERMISSION_LOG_DEBUG(
LABEL, "%{public}s: userInfos_[userId]: %{public}s", __func__, userInfos_[userId].ToString().c_str());
}
return userInfos_[userId];
}
void Root::GetUserGrantedUserInfo(std::vector<UserInfo>& bundleInfoList) const
{
for (auto it = userInfos_.begin(); it != userInfos_.end(); ++it) {
if (it->first != PermissionStateCache::SYSTEM_GRANTED_USER_ID) {
bundleInfoList.emplace_back(it->second);
}
}
}
std::string Root::ToString() const
{
std::string infos = R"({"Root": "Default", "UserInfos": [)";
for (auto userInfo : userInfos_) {
infos.append(userInfo.second.ToString() + ", ");
}
infos = infos + "]}";
return infos;
}
UserInfo::UserInfo(int userId)
{
userId_ = userId;
}
bool UserInfo::HasBundleInfo(const std::string& bundleName) const
{
return bundleInfos_.count(bundleName) == 1;
}
BundleInfo& UserInfo::GetOrCreateBundleInfo(const std::string& bundleName)
{
if (!HasBundleInfo(bundleName)) {
BundleInfo bundleInfo(bundleName);
bundleInfos_[bundleName] = bundleInfo;
}
return bundleInfos_[bundleName];
}
void UserInfo::GetAllBundleInfo(std::vector<BundleInfo>& bundleInfoList) const
{
for (auto it = bundleInfos_.begin(); it != bundleInfos_.end(); ++it) {
bundleInfoList.emplace_back(it->second);
}
}
std::string UserInfo::ToString() const
{
std::string infos = R"({"userId": )" + std::to_string(userId_) + R"(, "BundleInfos": [)";
for (auto bundleInfo : bundleInfos_) {
infos.append(bundleInfo.second.ToString() + ", ");
}
infos.append("]}");
return infos;
}
int UserInfo::ReplaceReqPermission(const std::string& bundleName, const PermissionReq& permissionReq)
{
return GetOrCreateBundleInfo(bundleName).ReplaceReqPermission(permissionReq);
}
int UserInfo::RemoveReqPermission(const std::string& bundleName)
{
if (!HasBundleInfo(bundleName)) {
return RET_SUCCESS;
}
bundleInfos_[bundleName].RemoveReqPermissions();
return RET_SUCCESS;
}
int UserInfo::UpdatePermissionState(const std::string& bundleName, const std::string& permissionName, bool isGranted)
{
if (!HasBundleInfo(bundleName)) {
return RET_FAILED;
}
return bundleInfos_[bundleName].UpdateGrantedState(permissionName, isGranted);
}
int UserInfo::UpdatePermissionFlags(const std::string& bundleName, const std::string& permissionName, int flags)
{
if (!HasBundleInfo(bundleName)) {
return RET_FAILED;
}
return bundleInfos_[bundleName].UpdatePermissionFlags(permissionName, flags);
}
bool UserInfo::IsGranted(const std::string& bundleName, const std::string& permissionName)
{
if (!HasBundleInfo(bundleName)) {
return false;
}
return bundleInfos_[bundleName].IsGranted(permissionName);
}
int UserInfo::GetPermissionFlags(const std::string& bundleName, const std::string& permissionName)
{
if (!HasBundleInfo(bundleName)) {
return DEFAULT_PERMISSION_FLAGS;
}
return bundleInfos_[bundleName].GetPermissionFlags(permissionName);
}
BundleInfo::BundleInfo(std::string bundleName)
{
bundleName_ = std::move(bundleName);
}
int BundleInfo::AddReqPermission(const std::string& permissionName)
{
if (HasReqPermission(permissionName)) {
PERMISSION_LOG_DEBUG(
LABEL, "%{public}s failed, reqPermission is exist, name: %{public}s", __func__, permissionName.c_str());
return RET_FAILED;
}
PermissionReq permissionReq = {permissionName, false, DEFAULT_PERMISSION_FLAGS};
permissionRequests_[permissionName] = permissionReq;
return RET_SUCCESS;
}
int BundleInfo::ReplaceReqPermission(const PermissionReq& permissionReq)
{
permissionRequests_[permissionReq.reqPermissionName] = permissionReq;
return RET_SUCCESS;
}
PermissionReq& BundleInfo::GetReqPermission(const std::string& permissionName)
{
return permissionRequests_[permissionName];
}
bool BundleInfo::HasReqPermission(const std::string& permissionName) const
{
return permissionRequests_.count(permissionName) == 1;
}
void BundleInfo::RemoveReqPermissions()
{
permissionRequests_.clear();
}
int BundleInfo::UpdateGrantedState(const std::string& permissionName, bool isGranted)
{
if (!HasReqPermission(permissionName)) {
return RET_FAILED;
}
GetReqPermission(permissionName).isGranted = isGranted;
return RET_SUCCESS;
}
int BundleInfo::UpdatePermissionFlags(const std::string& permissionName, int flags)
{
if (!HasReqPermission(permissionName)) {
return RET_FAILED;
}
GetReqPermission(permissionName).flags = flags;
return RET_SUCCESS;
}
bool BundleInfo::IsGranted(const std::string& permissionName)
{
if (!HasReqPermission(permissionName)) {
return false;
}
return GetReqPermission(permissionName).isGranted;
}
int BundleInfo::GetPermissionFlags(const std::string& permissionName)
{
if (!HasReqPermission(permissionName)) {
return DEFAULT_PERMISSION_FLAGS;
}
return GetReqPermission(permissionName).flags;
}
void BundleInfo::GetAllPermissionReq(std::vector<PermissionReq>& permissionReqList) const
{
for (auto it = permissionRequests_.begin(); it != permissionRequests_.end(); ++it) {
permissionReqList.emplace_back(it->second);
}
}
std::string BundleInfo::ToString() const
{
std::string infos = R"({"bundleName": ")" + bundleName_ + R"(", "ReqPermissions": [)";
for (const auto& request : permissionRequests_) {
PermissionReq permissionReq = request.second;
infos.append(R"({"permissionName": ")" + permissionReq.reqPermissionName + R"(")");
infos.append(R"(, "isGranted": )" + std::to_string(permissionReq.isGranted));
infos.append(R"(, "flags": )" + std::to_string(permissionReq.flags));
infos.append("}, ");
}
infos = infos + "]}";
return infos;
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,121 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_STANDARD_PERMISSION_STATE_CACHE_H
#define PERMISSION_STANDARD_PERMISSION_STATE_CACHE_H
#include <string>
#include <map>
#include <vector>
#include "permission_req.h"
#include "generic_values.h"
#include "data_translator.h"
#include "field_const.h"
#include "rwlock.h"
namespace OHOS {
namespace Security {
namespace Permission {
static const int DEFAULT_PERMISSION_FLAGS = 0;
class BundleInfo final {
public:
std::string bundleName_;
BundleInfo() = default;
virtual ~BundleInfo() = default;
explicit BundleInfo(std::string bundleName);
int AddReqPermission(const std::string& permissionName);
int ReplaceReqPermission(const PermissionReq& permissionReq);
PermissionReq& GetReqPermission(const std::string& permissionName);
void RemoveReqPermissions();
bool HasReqPermission(const std::string& permissionName) const;
int UpdateGrantedState(const std::string& permissionName, bool isGranted);
int UpdatePermissionFlags(const std::string& permissionName, int flags);
bool IsGranted(const std::string& permissionName);
int GetPermissionFlags(const std::string& permissionName);
void GetAllPermissionReq(std::vector<PermissionReq>& permissionReqList) const;
std::string ToString() const;
private:
std::map<std::string, PermissionReq> permissionRequests_;
};
class UserInfo final {
public:
int userId_;
UserInfo() : userId_(0)
{}
virtual ~UserInfo() = default;
explicit UserInfo(int userId);
bool HasBundleInfo(const std::string& bundleName) const;
BundleInfo& GetOrCreateBundleInfo(const std::string& bundleName);
int ReplaceReqPermission(const std::string& bundleName, const PermissionReq& permissionReq);
int RemoveReqPermission(const std::string& bundleName);
int UpdatePermissionState(const std::string& bundleName, const std::string& permissionName, bool isGranted);
int UpdatePermissionFlags(const std::string& bundleName, const std::string& permissionName, int flags);
bool IsGranted(const std::string& bundleName, const std::string& permissionName);
int GetPermissionFlags(const std::string& bundleName, const std::string& permissionName);
void GetAllBundleInfo(std::vector<BundleInfo>& bundleInfoList) const;
std::string ToString() const;
private:
std::map<std::string, BundleInfo> bundleInfos_;
};
class Root final {
public:
static Root& GetRoot();
bool HasUserInfo(int userId) const;
UserInfo& GetOrCreateUserInfo(int userId);
void GetUserGrantedUserInfo(std::vector<UserInfo>& userInfoList) const;
std::string ToString() const;
private:
std::map<int, UserInfo> userInfos_;
};
class PermissionStateCache final {
public:
static const int SYSTEM_GRANTED_USER_ID = -1;
static PermissionStateCache& GetInstance();
virtual ~PermissionStateCache() = default;
std::string ToString();
int AddReqPermission(int userId, const std::string& bundleName, const std::string& permissionName);
int AddReqPermission(int userId, const std::string& bundleName, const std::vector<std::string>& permList);
int ReplaceReqPermission(int userId, const std::string& bundleName, const PermissionReq& permissionReq);
int RemoveReqPermission(int userId, const std::string& bundleName);
int UpdatePermissionState(
int userId, const std::string& bundleName, const std::string& permissionName, bool isGranted);
int UpdatePermissionFlags(int userId, const std::string& bundleName, const std::string& permissionName, int flags);
bool IsGranted(int userId, const std::string& bundleName, const std::string& permissionName);
int GetPermissionFlags(int userId, const std::string& bundleName, const std::string& permissionName);
void QueryCurrentCache(bool isSystemGranted, std::vector<GenericValues>& valueList);
private:
PermissionStateCache() = default;
DISALLOW_COPY_AND_MOVE(PermissionStateCache);
void QueryForUser(const UserInfo& userInfo, std::vector<GenericValues>& valueList) const;
void QueryForBundle(const int userId, const BundleInfo& bundleInfo, std::vector<GenericValues>& valueList) const;
OHOS::Utils::RWLock cacheLock_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_STANDARD_PERMISSION_STATE_CACHE_H

View File

@ -0,0 +1,265 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_state_manager.h"
#include "permission.h"
#include "data_storage.h"
#include "permission_log.h"
#include "permission_definition_cache.h"
#include "permission_state_cache.h"
#include "data_translator.h"
#include "data_validator.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "PermissionStateManager"};
}
PermissionStateManager& PermissionStateManager::GetInstance()
{
static PermissionStateManager instance;
return instance;
}
PermissionStateManager::PermissionStateManager() : hasInited_(false)
{}
PermissionStateManager::~PermissionStateManager()
{
if (!hasInited_) {
return;
}
this->systemGrantedDataAccessWorker_.Stop();
this->userGrantedDataAccessWorker_.Stop();
this->hasInited_ = false;
}
void PermissionStateManager::Init()
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lk(this->rwLock_);
if (hasInited_) {
return;
}
PERMISSION_LOG_INFO(LABEL, "init begin!");
std::vector<GenericValues> results;
DataStorage::GetRealDataStorage().Find(DataStorage::PERMISSIONS_STAT_SYSTEM_GRANTED, results);
for (auto value : results) {
std::string bundleName = value.GetString(FIELD_BUNDLE_NAME);
PERMISSION_LOG_INFO(LABEL, "Cache recover system grant %{public}s", bundleName.c_str());
PermissionReq permissionReq;
DataTranslator::TranslationIntoPermissionReq(value, permissionReq);
PermissionStateCache::GetInstance().ReplaceReqPermission(
PermissionStateCache::SYSTEM_GRANTED_USER_ID, bundleName, permissionReq);
}
DataStorage::GetRealDataStorage().Find(DataStorage::PERMISSIONS_STAT_USER_GRANTED, results);
for (auto value : results) {
std::string bundleName = value.GetString(FIELD_BUNDLE_NAME);
int userId = value.GetInt(FIELD_USER_ID);
PERMISSION_LOG_INFO(LABEL, "Cache recover user grant %{public}d, %{public}s", userId, bundleName.c_str());
PermissionReq permissionReq;
DataTranslator::TranslationIntoPermissionReq(value, permissionReq);
PermissionStateCache::GetInstance().ReplaceReqPermission(userId, bundleName, permissionReq);
}
this->systemGrantedDataAccessWorker_.Start(1);
this->userGrantedDataAccessWorker_.Start(1);
hasInited_ = true;
PERMISSION_LOG_INFO(LABEL, "Init success");
}
void PermissionStateManager::AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId)
{
if (!DataValidator::IsBundleNameValid(bundleName) || permList.empty() || !DataValidator::IsUserIdValid(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
std::vector<GenericValues> values;
for (const auto& permission : permList) {
if (!PermissionDefinitionCache::GetInstance().IsUserGrantedPermission(permission)) {
PERMISSION_LOG_ERROR(LABEL,
"%{public}s: permission: %{public}s is not user-granted permission, check please!", __func__,
permission.c_str());
continue;
}
PermissionStateCache::GetInstance().AddReqPermission(userId, bundleName, permission);
}
RefreshUserGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId)
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsUserIdValid(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionStateCache::GetInstance().RemoveReqPermission(userId, bundleName);
RefreshUserGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::GrantUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName) ||
!DataValidator::IsUserIdValid(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionStateCache::GetInstance().UpdatePermissionState(userId, bundleName, permissionName, true);
RefreshUserGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::RevokeUserGrantedPermission(
const std::string& bundleName, const std::string& permissionName, int userId)
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName) ||
!DataValidator::IsUserIdValid(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionStateCache::GetInstance().UpdatePermissionState(userId, bundleName, permissionName, false);
RefreshUserGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::AddSystemGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList)
{
if (!DataValidator::IsBundleNameValid(bundleName) || permList.empty()) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
std::vector<GenericValues> values;
for (const auto& permission : permList) {
if (!PermissionDefinitionCache::GetInstance().IsSystemGrantedPermission(permission)) {
PERMISSION_LOG_ERROR(LABEL,
"%{public}s: permission: %{public}s is not system-granted permission, check please!", __func__,
permission.c_str());
continue;
}
PermissionStateCache::GetInstance().AddReqPermission(
PermissionStateCache::SYSTEM_GRANTED_USER_ID, bundleName, permission);
}
RefreshSystemGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::RemoveSystemGrantedReqPermissions(const std::string& bundleName)
{
if (!DataValidator::IsBundleNameValid(bundleName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionStateCache::GetInstance().RemoveReqPermission(PermissionStateCache::SYSTEM_GRANTED_USER_ID, bundleName);
RefreshSystemGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::GrantSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName)
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionStateCache::GetInstance().UpdatePermissionState(
PermissionStateCache::SYSTEM_GRANTED_USER_ID, bundleName, permissionName, true);
RefreshSystemGrantedPersistentDataIfNeeded();
}
void PermissionStateManager::RevokeSystemGrantedPermission(
const std::string& bundleName, const std::string& permissionName)
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return;
}
PermissionStateCache::GetInstance().UpdatePermissionState(
PermissionStateCache::SYSTEM_GRANTED_USER_ID, bundleName, permissionName, false);
RefreshSystemGrantedPersistentDataIfNeeded();
}
int PermissionStateManager::VerifyPermission(
const std::string& bundleName, const std::string& permissionName, int userId) const
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName) ||
!DataValidator::IsUserIdValid(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return PERMISSION_NOT_GRANTED;
}
if (!PermissionDefinitionCache::GetInstance().HasDefinition(permissionName)) {
PERMISSION_LOG_ERROR(
LABEL, "%{public}s: no definition for permission: %{public}s!", __func__, permissionName.c_str());
return PERMISSION_NOT_GRANTED;
}
bool isGranted = false;
if (PermissionDefinitionCache::GetInstance().IsSystemGrantedPermission(permissionName)) {
isGranted = PermissionStateCache::GetInstance().IsGranted(
PermissionStateCache::SYSTEM_GRANTED_USER_ID, bundleName, permissionName);
} else {
isGranted = PermissionStateCache::GetInstance().IsGranted(userId, bundleName, permissionName);
}
PERMISSION_LOG_INFO(LABEL, "VerifyPermission %{public}s, %{public}s, %{public}d isGranted: %{public}d",
bundleName.c_str(), permissionName.c_str(), userId, isGranted);
return isGranted ? PERMISSION_GRANTED : PERMISSION_NOT_GRANTED;
}
bool PermissionStateManager::CanRequestPermission(
const std::string& bundleName, const std::string& permissionName, int userId) const
{
if (!DataValidator::IsBundleNameValid(bundleName) || !DataValidator::IsPermissionNameValid(permissionName) ||
!DataValidator::IsUserIdValid(userId)) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: invalid params!", __func__);
return false;
}
return PermissionDefinitionCache::GetInstance().IsUserGrantedPermission(permissionName) &&
!PermissionStateCache::GetInstance().IsGranted(userId, bundleName, permissionName);
}
void PermissionStateManager::RefreshSystemGrantedPersistentDataIfNeeded()
{
if (systemGrantedDataAccessWorker_.GetCurTaskNum() > 1) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: has refresh task!", __func__);
return;
}
systemGrantedDataAccessWorker_.AddTask([]() {
std::vector<GenericValues> valueList;
PermissionStateCache::GetInstance().QueryCurrentCache(true, valueList);
DataStorage::GetRealDataStorage().RefreshAll(DataStorage::PERMISSIONS_STAT_SYSTEM_GRANTED, valueList);
// Sleep for one second to avoid frequent refresh of the database.
std::this_thread::sleep_for(std::chrono::seconds(1));
});
}
void PermissionStateManager::RefreshUserGrantedPersistentDataIfNeeded()
{
if (userGrantedDataAccessWorker_.GetCurTaskNum() > 1) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: has refresh task!", __func__);
return;
}
userGrantedDataAccessWorker_.AddTask([]() {
std::vector<GenericValues> valueList;
PermissionStateCache::GetInstance().QueryCurrentCache(false, valueList);
DataStorage::GetRealDataStorage().RefreshAll(DataStorage::PERMISSIONS_STAT_USER_GRANTED, valueList);
// Sleep for one second to avoid frequent refresh of the database.
std::this_thread::sleep_for(std::chrono::seconds(1));
});
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,80 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_STATE_MANAGER_H
#define PERMISSION_STATE_MANAGER_H
#include <vector>
#include "field_const.h"
#include "nocopyable.h"
#include "thread_pool.h"
#include "rwlock.h"
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionStateManager final {
public:
static PermissionStateManager& GetInstance();
virtual ~PermissionStateManager();
void Init();
void AddUserGrantedReqPermissions(
const std::string& bundleName, const std::vector<std::string>& permList, int userId);
void RemoveUserGrantedReqPermissions(const std::string& bundleName, int userId);
void GrantUserGrantedPermission(const std::string& bundleName, const std::string& permissionName, int userId);
void RevokeUserGrantedPermission(const std::string& bundleName, const std::string& permissionName, int userId);
void AddSystemGrantedReqPermissions(const std::string& bundleName, const std::vector<std::string>& permList);
void RemoveSystemGrantedReqPermissions(const std::string& bundleName);
void GrantSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName);
void RevokeSystemGrantedPermission(const std::string& bundleName, const std::string& permissionName);
int VerifyPermission(const std::string& bundleName, const std::string& permissionName, int userId) const;
bool CanRequestPermission(const std::string& bundleName, const std::string& permissionName, int userId) const;
private:
PermissionStateManager();
DISALLOW_COPY_AND_MOVE(PermissionStateManager);
void RefreshSystemGrantedPersistentDataIfNeeded();
void RefreshUserGrantedPersistentDataIfNeeded();
OHOS::ThreadPool systemGrantedDataAccessWorker_;
OHOS::ThreadPool userGrantedDataAccessWorker_;
bool hasInited_;
OHOS::Utils::RWLock rwLock_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_STATE_MANAGER_H

View File

@ -0,0 +1,188 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "sqlite_helper.h"
#include "permission_log.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "SqliteHelper"};
}
SqliteHelper::SqliteHelper(const std::string& dbName, const std::string& dbPath, int version)
: dbName_(dbName), dbPath_(dbPath), currentVersion_(version), db_(nullptr)
{}
SqliteHelper::~SqliteHelper()
{}
void SqliteHelper::Open()
{
if (db_ != nullptr) {
return;
}
if (dbName_.empty() || dbPath_.empty() || currentVersion_ < 0) {
return;
}
std::string fileName = dbPath_ + dbName_;
int res = sqlite3_open(fileName.c_str(), &db_);
if (res != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "Failed to open db: %{public}s", sqlite3_errmsg(db_));
return;
}
int version = GetVersion();
if (version == currentVersion_) {
return;
}
BeginTransaction();
if (version == 0) {
OnCreate();
} else {
if (version < currentVersion_) {
OnUpdate();
}
}
SetVersion();
CommitTransaction();
}
void SqliteHelper::Close()
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return;
}
int ret = sqlite3_close(db_);
if (ret != SQLITE_OK) {
PERMISSION_LOG_WARN(LABEL, "sqlite3_close error, ret=%{public}d", ret);
return;
}
db_ = nullptr;
}
int SqliteHelper::BeginTransaction() const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return GENERAL_ERROR;
}
char* errorMessage = nullptr;
int result = 0;
int ret = sqlite3_exec(db_, "BEGIN;", nullptr, nullptr, &errorMessage);
if (ret != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage);
result = GENERAL_ERROR;
}
sqlite3_free(errorMessage);
return result;
}
int SqliteHelper::CommitTransaction() const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return GENERAL_ERROR;
}
char* errorMessage = nullptr;
int result = 0;
int ret = sqlite3_exec(db_, "COMMIT;", nullptr, nullptr, &errorMessage);
if (ret != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage);
result = GENERAL_ERROR;
}
sqlite3_free(errorMessage);
return result;
}
int SqliteHelper::RollbackTransaction() const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return GENERAL_ERROR;
}
int result = 0;
char* errorMessage = nullptr;
int ret = sqlite3_exec(db_, "ROLLBACK;", nullptr, nullptr, &errorMessage);
if (ret != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage);
result = GENERAL_ERROR;
}
sqlite3_free(errorMessage);
return result;
}
Statement SqliteHelper::Prepare(const std::string& sql) const
{
return Statement(db_, sql);
}
int SqliteHelper::ExecuteSql(const std::string& sql) const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return GENERAL_ERROR;
}
char* errorMessage = nullptr;
int result = 0;
int res = sqlite3_exec(db_, sql.c_str(), nullptr, nullptr, &errorMessage);
if (res != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, errorMessage);
result = GENERAL_ERROR;
}
sqlite3_free(errorMessage);
return result;
}
int SqliteHelper::GetVersion() const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return GENERAL_ERROR;
}
auto statement = Prepare(PRAGMA_VERSION_COMMAND);
int version = 0;
while (statement.Step() == Statement::State::ROW) {
version = statement.GetColumnInt(0);
}
PERMISSION_LOG_INFO(LABEL, "%{public}s: version: %{public}d", __func__, version);
return version;
}
void SqliteHelper::SetVersion() const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return;
}
auto statement = Prepare(PRAGMA_VERSION_COMMAND + " = " + std::to_string(currentVersion_));
statement.Step();
}
std::string SqliteHelper::SpitError() const
{
if (db_ == nullptr) {
PERMISSION_LOG_WARN(LABEL, "%{public}s: do open data base first!", __func__);
return "";
}
return sqlite3_errmsg(db_);
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,62 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef SQLITE_HELPER_H
#define SQLITE_HELPER_H
#include <string>
#include "statement.h"
#include "sqlite3sym.h"
namespace OHOS {
namespace Security {
namespace Permission {
class SqliteHelper {
public:
explicit SqliteHelper(const std::string& dbName, const std::string& dbPath, int version);
virtual ~SqliteHelper();
void Open();
void Close();
int BeginTransaction() const;
int CommitTransaction() const;
int RollbackTransaction() const;
Statement Prepare(const std::string& sql) const;
int ExecuteSql(const std::string& sql) const;
std::string SpitError() const;
virtual void OnCreate() = 0;
virtual void OnUpdate() = 0;
private:
inline static const std::string PRAGMA_VERSION_COMMAND = "PRAGMA user_version";
static const int GENERAL_ERROR = -1;
const std::string dbName_;
const std::string dbPath_;
int currentVersion_;
sqlite3* db_;
int GetVersion() const;
void SetVersion() const;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // SQLITE_HELPER_H

View File

@ -0,0 +1,337 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "sqlite_storage.h"
#include "permission_log.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "SqliteStorage"};
}
SqliteStorage& SqliteStorage::GetInstance()
{
static SqliteStorage instance;
return instance;
}
SqliteStorage::~SqliteStorage()
{
Close();
}
void SqliteStorage::OnCreate()
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called.", __func__);
CreatePermissionDefinitionTable();
CreateSystemGrantedPermissionStateTable();
CreateUserGrantedPermissionStateTable();
}
void SqliteStorage::OnUpdate()
{
PERMISSION_LOG_INFO(LABEL, "%{public}s called.", __func__);
}
SqliteStorage::SqliteStorage() : SqliteHelper(DATABASE_NAME, DATABASE_PATH, DATABASE_VERSION)
{
SqliteTable permissionDefTable;
permissionDefTable.tableName_ = PERMISSION_DEF_TABLE;
permissionDefTable.tableColumnNames_ = {
FIELD_PERMISSION_NAME,
FIELD_BUNDLE_NAME,
FIELD_GRANT_MODE,
FIELD_AVAILABLE_SCOPE,
FIELD_LABEL,
FIELD_LABEL_ID,
FIELD_DESCRIPTION,
FIELD_DESCRIPTION_ID
};
SqliteTable sysGrantPermStatTable;
sysGrantPermStatTable.tableName_ = SYS_GRANTED_PERMISSION_STATE_TABLE;
sysGrantPermStatTable.tableColumnNames_ = {
FIELD_BUNDLE_NAME,
FIELD_PERMISSION_NAME,
FIELD_GRANTED,
FIELD_FLAGS
};
SqliteTable userGrantPermStatTable;
userGrantPermStatTable.tableName_ = USER_GRANTED_PERMISSION_STATE_TABLE;
userGrantPermStatTable.tableColumnNames_ = {
FIELD_BUNDLE_NAME,
FIELD_PERMISSION_NAME,
FIELD_USER_ID,
FIELD_GRANTED,
FIELD_FLAGS
};
dataTypeToSqlTable_ = {
{PERMISSION_DEF, permissionDefTable},
{PERMISSIONS_STAT_SYSTEM_GRANTED, sysGrantPermStatTable},
{PERMISSIONS_STAT_USER_GRANTED, userGrantPermStatTable}
};
Open();
}
int SqliteStorage::Add(const DataType type, const std::vector<GenericValues>& values)
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lock(this->rwLock_);
std::string prepareSql = CreateInsertPrepareSqlCmd(type);
auto statement = Prepare(prepareSql);
BeginTransaction();
bool isExecuteSuccessfully = true;
for (auto value : values) {
std::vector<std::string> columnNames = value.GetAllKeys();
for (auto columnName : columnNames) {
statement.Bind(columnName, value.Get(columnName));
}
int ret = statement.Step();
if (ret != Statement::State::DONE) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: failed, errorMsg: %{public}s", __func__, SpitError().c_str());
isExecuteSuccessfully = false;
}
statement.Reset();
}
if (!isExecuteSuccessfully) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: rollback transaction.", __func__);
RollbackTransaction();
return FAILURE;
}
PERMISSION_LOG_INFO(LABEL, "%{public}s: commit transaction.", __func__);
CommitTransaction();
return SUCCESS;
}
int SqliteStorage::Remove(const DataType type, const GenericValues& conditions)
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lock(this->rwLock_);
std::vector<std::string> columnNames = conditions.GetAllKeys();
std::string prepareSql = CreateDeletePrepareSqlCmd(type, columnNames);
auto statement = Prepare(prepareSql);
for (auto columnName : columnNames) {
statement.Bind(columnName, conditions.Get(columnName));
}
int ret = statement.Step();
return (ret == Statement::State::DONE) ? SUCCESS : FAILURE;
}
int SqliteStorage::Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions)
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lock(this->rwLock_);
std::vector<std::string> modifyColumns = modifyValues.GetAllKeys();
std::vector<std::string> conditionColumns = conditions.GetAllKeys();
std::string prepareSql = CreateUpdatePrepareSqlCmd(type, modifyColumns, conditionColumns);
auto statement = Prepare(prepareSql);
for (auto columnName : modifyColumns) {
statement.Bind(columnName, modifyValues.Get(columnName));
}
for (auto columnName : conditionColumns) {
statement.Bind(columnName, conditions.Get(columnName));
}
int ret = statement.Step();
return (ret == Statement::State::DONE) ? SUCCESS : FAILURE;
}
int SqliteStorage::Find(const DataType type, std::vector<GenericValues>& results)
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lock(this->rwLock_);
std::string prepareSql = CreateSelectPrepareSqlCmd(type);
auto statement = Prepare(prepareSql);
while (statement.Step() == Statement::State::ROW) {
int columnCount = statement.GetColumnCount();
GenericValues value;
for (int i = 0; i < columnCount; i++) {
value.Put(statement.GetColumnName(i), statement.GetValue(i));
}
results.emplace_back(value);
}
return SUCCESS;
}
int SqliteStorage::RefreshAll(const DataType type, const std::vector<GenericValues>& values)
{
OHOS::Utils::UniqueWriteGuard<OHOS::Utils::RWLock> lock(this->rwLock_);
std::string deleteSql = CreateDeletePrepareSqlCmd(type);
std::string insertSql = CreateInsertPrepareSqlCmd(type);
auto deleteStatement = Prepare(deleteSql);
auto insertStatement = Prepare(insertSql);
BeginTransaction();
bool canCommit = deleteStatement.Step() == Statement::State::DONE;
for (auto value : values) {
std::vector<std::string> columnNames = value.GetAllKeys();
for (auto columnName : columnNames) {
insertStatement.Bind(columnName, value.Get(columnName));
}
int ret = insertStatement.Step();
if (ret != Statement::State::DONE) {
PERMISSION_LOG_ERROR(
LABEL, "%{public}s: insert failed, errorMsg: %{public}s", __func__, SpitError().c_str());
canCommit = false;
}
insertStatement.Reset();
}
if (!canCommit) {
PERMISSION_LOG_ERROR(LABEL, "%{public}s: rollback transaction.", __func__);
RollbackTransaction();
return FAILURE;
}
PERMISSION_LOG_INFO(LABEL, "%{public}s: commit transaction.", __func__);
CommitTransaction();
return SUCCESS;
}
std::string SqliteStorage::CreateInsertPrepareSqlCmd(const DataType type) const
{
auto it = dataTypeToSqlTable_.find(type);
if (it == dataTypeToSqlTable_.end()) {
return std::string();
}
std::string sql = "insert into " + it->second.tableName_ + " values(";
int i = 1;
for (const auto& columnName : it->second.tableColumnNames_) {
sql.append(":" + columnName);
if (i < (int) it->second.tableColumnNames_.size()) {
sql.append(",");
}
i += 1;
}
sql.append(")");
return sql;
}
std::string SqliteStorage::CreateDeletePrepareSqlCmd(
const DataType type, const std::vector<std::string>& columnNames) const
{
auto it = dataTypeToSqlTable_.find(type);
if (it == dataTypeToSqlTable_.end()) {
return std::string();
}
std::string sql = "delete from " + it->second.tableName_ + " where 1 = 1";
for (auto columnName : columnNames) {
sql.append(" and ");
sql.append(columnName + "=:" + columnName);
}
return sql;
}
std::string SqliteStorage::CreateUpdatePrepareSqlCmd(const DataType type, const std::vector<std::string>& modifyColumns,
const std::vector<std::string>& conditionColumns) const
{
if (modifyColumns.empty()) {
return std::string();
}
auto it = dataTypeToSqlTable_.find(type);
if (it == dataTypeToSqlTable_.end()) {
return std::string();
}
std::string sql = "update " + it->second.tableName_ + " set ";
int i = 1;
for (const auto& columnName : modifyColumns) {
sql.append(columnName + "=:" + columnName);
if (i < (int) modifyColumns.size()) {
sql.append(",");
}
i += 1;
}
if (!conditionColumns.empty()) {
sql.append(" where 1 = 1");
for (const auto& columnName : conditionColumns) {
sql.append(" and ");
sql.append(columnName + "=:" + columnName);
}
}
return sql;
}
std::string SqliteStorage::CreateSelectPrepareSqlCmd(const DataType type) const
{
auto it = dataTypeToSqlTable_.find(type);
if (it == dataTypeToSqlTable_.end()) {
return std::string();
}
std::string sql = "select * from " + it->second.tableName_;
return sql;
}
int SqliteStorage::CreatePermissionDefinitionTable() const
{
auto it = dataTypeToSqlTable_.find(DataType::PERMISSION_DEF);
if (it == dataTypeToSqlTable_.end()) {
return FAILURE;
}
std::string sql = "create table if not exists ";
sql.append(it->second.tableName_ + " (")
.append(FIELD_PERMISSION_NAME + " text not null,")
.append(FIELD_BUNDLE_NAME + " text not null,")
.append(FIELD_GRANT_MODE + " integer not null,")
.append(FIELD_AVAILABLE_SCOPE + " integer not null,")
.append(FIELD_LABEL + " text not null,")
.append(FIELD_LABEL_ID + " integer not null,")
.append(FIELD_DESCRIPTION + " text not null,")
.append(FIELD_DESCRIPTION_ID + " integer not null,")
.append("primary key(" + FIELD_PERMISSION_NAME)
.append("))");
return ExecuteSql(sql);
}
int SqliteStorage::CreateSystemGrantedPermissionStateTable() const
{
auto it = dataTypeToSqlTable_.find(DataType::PERMISSIONS_STAT_SYSTEM_GRANTED);
if (it == dataTypeToSqlTable_.end()) {
return FAILURE;
}
std::string sql = "create table if not exists ";
sql.append(it->second.tableName_ + " (")
.append(FIELD_BUNDLE_NAME + " text not null,")
.append(FIELD_PERMISSION_NAME + " text not null,")
.append(FIELD_GRANTED + " integer not null,")
.append(FIELD_FLAGS + " integer not null,")
.append("primary key(" + FIELD_BUNDLE_NAME)
.append("," + FIELD_PERMISSION_NAME)
.append("))");
return ExecuteSql(sql);
}
int SqliteStorage::CreateUserGrantedPermissionStateTable() const
{
auto it = dataTypeToSqlTable_.find(DataType::PERMISSIONS_STAT_USER_GRANTED);
if (it == dataTypeToSqlTable_.end()) {
return FAILURE;
}
std::string sql = "create table if not exists ";
sql.append(it->second.tableName_ + " (")
.append(FIELD_BUNDLE_NAME + " text not null,")
.append(FIELD_PERMISSION_NAME + " text not null,")
.append(FIELD_USER_ID + " integer not null,")
.append(FIELD_GRANTED + " integer not null,")
.append(FIELD_FLAGS + " integer not null,")
.append("primary key(" + FIELD_BUNDLE_NAME)
.append("," + FIELD_PERMISSION_NAME)
.append("," + FIELD_USER_ID)
.append("))");
return ExecuteSql(sql);
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,86 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef SQLITE_STORAGE_H
#define SQLITE_STORAGE_H
#include "data_storage.h"
#include "sqlite_helper.h"
#include "field_const.h"
#include "nocopyable.h"
#include "rwlock.h"
namespace OHOS {
namespace Security {
namespace Permission {
class SqliteStorage : public DataStorage, public SqliteHelper {
public:
enum ExecuteResult { FAILURE = -1, SUCCESS };
struct SqliteTable {
public:
std::string tableName_;
std::vector<std::string> tableColumnNames_;
};
static SqliteStorage& GetInstance();
~SqliteStorage() override;
int Add(const DataType type, const std::vector<GenericValues>& values) override;
int Remove(const DataType type, const GenericValues& conditions) override;
int Modify(const DataType type, const GenericValues& modifyValues, const GenericValues& conditions) override;
int Find(const DataType type, std::vector<GenericValues>& results) override;
int RefreshAll(const DataType type, const std::vector<GenericValues>& values) override;
void OnCreate() override;
void OnUpdate() override;
private:
SqliteStorage();
DISALLOW_COPY_AND_MOVE(SqliteStorage);
std::map<DataType, SqliteTable> dataTypeToSqlTable_;
OHOS::Utils::RWLock rwLock_;
int CreatePermissionDefinitionTable() const;
int CreateSystemGrantedPermissionStateTable() const;
int CreateUserGrantedPermissionStateTable() const;
std::string CreateInsertPrepareSqlCmd(const DataType type) const;
std::string CreateDeletePrepareSqlCmd(
const DataType type, const std::vector<std::string>& columnNames = std::vector<std::string>()) const;
std::string CreateUpdatePrepareSqlCmd(const DataType type, const std::vector<std::string>& modifyColumns,
const std::vector<std::string>& conditionColumns) const;
std::string CreateSelectPrepareSqlCmd(const DataType type) const;
private:
inline static const std::string PERMISSION_DEF_TABLE = "permission_definition_table";
inline static const std::string SYS_GRANTED_PERMISSION_STATE_TABLE = "system_granted_permission_state_table";
inline static const std::string USER_GRANTED_PERMISSION_STATE_TABLE = "user_granted_permission_state_table";
inline static const std::string DATABASE_NAME = "permission.db";
inline static const std::string DATABASE_PATH = "/data/system/";
static const int DATABASE_VERSION = 1;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // SQLITE_STORAGE_H

View File

@ -0,0 +1,125 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "statement.h"
#include "permission_log.h"
namespace OHOS {
namespace Security {
namespace Permission {
namespace {
static constexpr OHOS::HiviewDFX::HiLogLabel LABEL = {LOG_CORE, SECURITY_DOMAIN_PERMISSION, "Statement"};
}
Statement::Statement(sqlite3* db, const std::string& sql) : db_(db), sql_(sql)
{
if (sqlite3_prepare_v2(db, sql.c_str(), sql.size(), &statement_, nullptr) != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "Cannot prepare, errorMsg: %{public}s", sqlite3_errmsg(db_));
}
}
Statement::~Statement()
{
sqlite3_finalize(statement_);
statement_ = nullptr;
}
void Statement::Bind(const int index, const std::string& text)
{
if (sqlite3_bind_text(statement_, index, text.c_str(), text.size(), SQLITE_TRANSIENT) != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "Cannot bind string, errorMsg: %{public}s", sqlite3_errmsg(db_));
}
}
void Statement::Bind(const int index, int value)
{
if (sqlite3_bind_int(statement_, index, value) != SQLITE_OK) {
PERMISSION_LOG_ERROR(LABEL, "Cannot bind int, errorMsg: %{public}s", sqlite3_errmsg(db_));
}
}
int Statement::GetColumnInt(const int column) const
{
return sqlite3_column_int(statement_, column);
}
std::string Statement::GetColumnString(const int column) const
{
return std::string(reinterpret_cast<const char*>(sqlite3_column_text(statement_, column)));
}
std::string Statement::GetColumnName(const int column) const
{
return sqlite3_column_name(statement_, column);
}
Statement::State Statement::Step()
{
int ret = sqlite3_step(statement_);
switch (ret) {
case SQLITE_ROW:
return Statement::State::ROW;
case SQLITE_DONE:
return Statement::State::DONE;
case SQLITE_BUSY:
return Statement::State::BUSY;
case SQLITE_MISUSE:
return Statement::State::MISUSE;
default:
return Statement::State::UNKNOWN;
}
}
int Statement::GetParameterIndex(const std::string& name) const
{
return sqlite3_bind_parameter_index(statement_, name.c_str());
}
void Statement::Bind(const std::string& tableColumnName, const VariantValue& value)
{
int index = GetParameterIndex(":" + tableColumnName);
if (value.GetType() == ValueType::TYPE_STRING) {
Bind(index, value.GetString());
} else if (value.GetType() == ValueType::TYPE_INT) {
Bind(index, value.GetInt());
}
}
int Statement::Reset()
{
return sqlite3_reset(statement_);
}
int Statement::GetColumnCount() const
{
return sqlite3_column_count(statement_);
}
VariantValue Statement::GetValue(const int column) const
{
int type = sqlite3_column_type(statement_, column);
switch (type) {
case SQLITE_INTEGER:
return VariantValue(GetColumnInt(column));
case SQLITE_TEXT:
return VariantValue(GetColumnString(column));
default:
return VariantValue();
}
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,57 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef STATEMENT_H
#define STATEMENT_H
#include <string>
#include "variant_value.h"
#include "sqlite3sym.h"
namespace OHOS {
namespace Security {
namespace Permission {
class Statement final {
public:
enum State { BUSY, ROW, DONE, MISUSE, UNKNOWN };
Statement(sqlite3* db, const std::string& sql);
virtual ~Statement();
void Bind(const int index, const std::string& text);
void Bind(const int index, int value);
void Bind(const std::string& tableColumnName, const VariantValue& value);
State Step();
int Reset();
std::string GetColumnString(const int column) const;
int GetColumnInt(const int column) const;
std::string GetColumnName(const int column) const;
int GetParameterIndex(const std::string& name) const;
int GetColumnCount() const;
VariantValue GetValue(const int column) const;
private:
sqlite3* db_;
sqlite3_stmt* statement_;
const std::string sql_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // STATEMENT_H

View File

@ -0,0 +1,61 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "variant_value.h"
namespace OHOS {
namespace Security {
namespace Permission {
VariantValue::VariantValue() : type_(ValueType::TYPE_NULL)
{}
VariantValue::~VariantValue()
{}
VariantValue::VariantValue(int value) : type_(ValueType::TYPE_INT)
{
value_ = value;
}
VariantValue::VariantValue(const std::string& value) : type_(ValueType::TYPE_STRING)
{
value_ = value;
}
ValueType VariantValue::GetType() const
{
return type_;
}
int VariantValue::GetInt() const
{
if (type_ != ValueType::TYPE_INT) {
return DEFAULT_VALUE;
}
return std::get<int>(value_);
}
std::string VariantValue::GetString() const
{
if (type_ != ValueType::TYPE_STRING) {
return std::string();
}
return std::get<std::string>(value_);
}
} // namespace Permission
} // namespace Security
} // namespace OHOS

View File

@ -0,0 +1,52 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef VARIANT_VALUE_H
#define VARIANT_VALUE_H
#include <string>
#include <variant>
namespace OHOS {
namespace Security {
namespace Permission {
enum class ValueType {
TYPE_NULL,
TYPE_INT,
TYPE_STRING,
};
class VariantValue final {
public:
VariantValue();
virtual ~VariantValue();
explicit VariantValue(int value);
explicit VariantValue(const std::string& value);
ValueType GetType() const;
int GetInt() const;
std::string GetString() const;
static const int DEFAULT_VALUE = -1;
private:
ValueType type_;
std::variant<int, std::string> value_;
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // VARIANT_VALUE_H

View File

@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Copyright (C) 2021 Huawei Device Co., Ltd.
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.
-->
<info>
<process>foundation</process>
<systemability>
<name>3501</name>
<libpath>libpermission_manager_service_standard.z.so</libpath>
<run-on-create>true</run-on-create>
<distributed>false</distributed>
<dump-level>1</dump-level>
</systemability>
</info>

View File

@ -0,0 +1,20 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/ohos/sa_profile/sa_profile.gni")
ohos_sa_profile("permission_sa_profile_standard") {
part_name = "permission_standard"
sources = [ "3501.xml" ]
}

View File

@ -0,0 +1,48 @@
# Copyright (c) 2021 Huawei Device Co., Ltd.
# 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.
import("//build/test.gni")
ohos_unittest("libpermission_manager_service_standard_test") {
subsystem_name = "security"
part_name = "permission_standard"
module_out_path = part_name + "/" + part_name
include_dirs = [
"//utils/native/base/include",
"//base/security/permission/interfaces/innerkits/permission_standard/permissionsdk/main/cpp/include/permission",
"//base/security/permission/services/permission_standard/permissionmanagerservice/main/cpp/src/",
]
sources = [
"unittest/cpp/src/permission_definition_manager_test.cpp",
"unittest/cpp/src/permission_state_manager_test.cpp",
]
cflags_cc = [ "-DHILOG_ENABLE" ]
deps = [
"//base/security/permission/frameworks/permission_standard/permissioncommunicationadapter:permission_standard_communication_adapter_cxx",
"//base/security/permission/frameworks/permission_standard/permissioninfrastructure:permission_standard_infrastructure_cxx",
"//base/security/permission/services/permission_standard/permissionmanagerservice:permission_manager_service_standard",
"//third_party/googletest:gtest_main",
"//utils/native/base:utils",
]
external_deps = [ "hiviewdfx_hilog_native:libhilog" ]
}
group("unittest") {
testonly = true
deps = [ ":libpermission_manager_service_standard_test" ]
}

View File

@ -0,0 +1,88 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_definition_manager_test.h"
#include <string>
#include "permission_definition_manager.h"
#include "permission.h"
#include "test_const.h"
using namespace testing::ext;
using namespace OHOS::Security::Permission;
void PermissionDefinitionManagerTest::SetUpTestCase()
{}
void PermissionDefinitionManagerTest::TearDownTestCase()
{}
void PermissionDefinitionManagerTest::SetUp()
{}
void PermissionDefinitionManagerTest::TearDown()
{
PermissionDefinitionManager::GetInstance().RemoveDefPermissions(TEST_BUNDLE_NAME);
}
HWTEST_F(PermissionDefinitionManagerTest, AddDefPermissions001, TestSize.Level1)
{
vector<PermissionDefParcel> defs;
PermissionDefParcel permissionDefParcel;
permissionDefParcel.permissionDef.permissionName = TEST_PERMISSION_NAME_ALPHA;
permissionDefParcel.permissionDef.bundleName = TEST_BUNDLE_NAME;
permissionDefParcel.permissionDef.grantMode = GrantMode::SYSTEM_GRANT;
permissionDefParcel.permissionDef.availableScope = AvailableScope::AVAILABLE_SCOPE_ALL;
permissionDefParcel.permissionDef.label = TEST_LABEL;
permissionDefParcel.permissionDef.labelId = TEST_LABEL_ID;
permissionDefParcel.permissionDef.description = TEST_DESCRIPTION;
permissionDefParcel.permissionDef.descriptionId = TEST_DESCRIPTION_ID;
defs.emplace_back(permissionDefParcel);
PermissionDefinitionManager::GetInstance().AddDefPermissions(defs);
PermissionDefParcel result;
PermissionDefinitionManager::GetInstance().GetDefPermission(TEST_PERMISSION_NAME_ALPHA, result);
ASSERT_EQ(TEST_PERMISSION_NAME_ALPHA, result.permissionDef.permissionName);
ASSERT_EQ(TEST_BUNDLE_NAME, result.permissionDef.bundleName);
ASSERT_EQ(GrantMode::SYSTEM_GRANT, result.permissionDef.grantMode);
ASSERT_EQ(AvailableScope::AVAILABLE_SCOPE_ALL, result.permissionDef.availableScope);
ASSERT_EQ(TEST_LABEL, result.permissionDef.label);
ASSERT_EQ(TEST_LABEL_ID, result.permissionDef.labelId);
ASSERT_EQ(TEST_DESCRIPTION, result.permissionDef.description);
ASSERT_EQ(TEST_DESCRIPTION_ID, result.permissionDef.descriptionId);
}
HWTEST_F(PermissionDefinitionManagerTest, RemoveDefPermissions001, TestSize.Level1)
{
vector<PermissionDefParcel> defs;
PermissionDefParcel permissionDefParcel;
permissionDefParcel.permissionDef.permissionName = TEST_PERMISSION_NAME_ALPHA;
permissionDefParcel.permissionDef.bundleName = TEST_BUNDLE_NAME;
permissionDefParcel.permissionDef.grantMode = GrantMode::SYSTEM_GRANT;
permissionDefParcel.permissionDef.availableScope = AVAILABLE_SCOPE_SIGNATURE;
defs.emplace_back(permissionDefParcel);
PermissionDefinitionManager::GetInstance().AddDefPermissions(defs);
PermissionDefParcel result;
int ret = PermissionDefinitionManager::GetInstance().GetDefPermission(TEST_PERMISSION_NAME_ALPHA, result);
ASSERT_EQ(RET_SUCCESS, ret);
PermissionDefinitionManager::GetInstance().RemoveDefPermissions(TEST_BUNDLE_NAME);
PermissionDefParcel defParcel;
ret = PermissionDefinitionManager::GetInstance().GetDefPermission(TEST_PERMISSION_NAME_ALPHA, defParcel);
ASSERT_EQ(RET_FAILED, ret);
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_DEFINITION_MANAGER_TEST_H
#define PERMISSION_DEFINITION_MANAGER_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionDefinitionManagerTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp();
void TearDown();
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_DEFINITION_MANAGER_TEST_H

View File

@ -0,0 +1,44 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#include "permission_state_manager_test.h"
#include <string>
#include "permission_state_manager.h"
#include "test_const.h"
using namespace testing::ext;
using namespace OHOS::Security::Permission;
void PermissionStateManagerTest::SetUpTestCase()
{}
void PermissionStateManagerTest::TearDownTestCase()
{}
void PermissionStateManagerTest::SetUp()
{}
void PermissionStateManagerTest::TearDown()
{}
HWTEST_F(PermissionStateManagerTest, AddUserGrantedReqPermissions001, TestSize.Level1)
{
std::vector<std::string> permList;
permList.emplace_back(TEST_PERMISSION_NAME_ALPHA);
PermissionStateManager::GetInstance().AddUserGrantedReqPermissions(TEST_BUNDLE_NAME, permList, 0);
PermissionStateManager::GetInstance().AddUserGrantedReqPermissions(TEST_BUNDLE_NAME, permList, TEST_SUB_USER_ID);
}

View File

@ -0,0 +1,37 @@
/*
* Copyright (c) 2021 Huawei Device Co., Ltd.
* 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.
*/
#ifndef PERMISSION_STATE_MANAGER_TEST_H
#define PERMISSION_STATE_MANAGER_TEST_H
#include <gtest/gtest.h>
namespace OHOS {
namespace Security {
namespace Permission {
class PermissionStateManagerTest : public testing::Test {
public:
static void SetUpTestCase();
static void TearDownTestCase();
void SetUp();
void TearDown();
};
} // namespace Permission
} // namespace Security
} // namespace OHOS
#endif // PERMISSION_STATE_MANAGER_TEST_H