1 /*
2  * Copyright (c) 2024 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 #define LOG_TAG "DataSharePermission"
16 
17 #include "data_share_permission.h"
18 
19 #include <string>
20 
21 #include "data_share_called_config.h"
22 #include "datashare_errno.h"
23 #include "datashare_log.h"
24 #include "datashare_string_utils.h"
25 
26 namespace OHOS {
27 namespace DataShare {
28 using namespace AppExecFwk;
VerifyPermission(Security::AccessToken::AccessTokenID tokenID,const Uri & uri,bool isRead)29 int DataSharePermission::VerifyPermission(Security::AccessToken::AccessTokenID tokenID, const Uri &uri, bool isRead)
30 {
31     if (uri.ToString().empty()) {
32         LOG_ERROR("Uri empty, tokenId:0x%{public}x", tokenID);
33         return ERR_INVALID_VALUE;
34     }
35     DataShareCalledConfig calledConfig(uri.ToString());
36     auto [errCode, providerInfo] = calledConfig.GetProviderInfo(tokenID);
37     if (errCode != E_OK) {
38         LOG_ERROR("ProviderInfo failed! token:0x%{public}x, errCode:%{public}d,uri:%{public}s", tokenID,
39             errCode, DataShareStringUtils::Anonymous(uri.ToString()).c_str());
40         return errCode;
41     }
42     auto permission = isRead ? providerInfo.readPermission : providerInfo.writePermission;
43     if (permission.empty()) {
44         LOG_ERROR("Reject, tokenId:0x%{public}x, uri:%{public}s", tokenID,
45             DataShareStringUtils::Anonymous(providerInfo.uri).c_str());
46         return ERR_PERMISSION_DENIED;
47     }
48     int status =
49         Security::AccessToken::AccessTokenKit::VerifyAccessToken(tokenID, permission);
50     if (status != Security::AccessToken::PermissionState::PERMISSION_GRANTED) {
51         LOG_ERROR("Permission denied! token:0x%{public}x,permission:%{public}s,uri:%{public}s",
52             tokenID, permission.c_str(), DataShareStringUtils::Anonymous(providerInfo.uri).c_str());
53         return ERR_PERMISSION_DENIED;
54     }
55     return E_OK;
56 }
57 } // namespace DataShare
58 } // namespace OHOS