1 /*
2 * Copyright (c) 2023 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
16 //! This module is used to provide common capabilities for the Asset operations.
17
18 mod argument_check;
19 mod permission_check;
20
21 pub(crate) use argument_check::{
22 check_group_validity, check_required_tags, check_tag_validity, check_value_validity, MAX_LABEL_SIZE,
23 };
24 pub(crate) use permission_check::check_system_permission;
25
26 use asset_common::{CallingInfo, OWNER_INFO_SEPARATOR};
27 use asset_crypto_manager::secret_key::SecretKey;
28 use asset_db_operator::types::{column, DbMap, DB_DATA_VERSION, DB_DATA_VERSION_V1};
29 use asset_definition::{
30 log_throw_error, Accessibility, AssetMap, AuthType, ErrCode, Extension, OperationType, Result, Tag, Value,
31 };
32 use asset_log::{loge, logi};
33 use asset_plugin::asset_plugin::AssetPlugin;
34 use asset_sdk::plugin_interface::{EventType, ExtDbMap, PARAM_NAME_BUNDLE_NAME, PARAM_NAME_USER_ID};
35
36 const TAG_COLUMN_TABLE: [(Tag, &str); 21] = [
37 (Tag::Secret, column::SECRET),
38 (Tag::Alias, column::ALIAS),
39 (Tag::Accessibility, column::ACCESSIBILITY),
40 (Tag::AuthType, column::AUTH_TYPE),
41 (Tag::SyncType, column::SYNC_TYPE),
42 (Tag::UpdateTime, column::UPDATE_TIME),
43 (Tag::IsPersistent, column::IS_PERSISTENT),
44 (Tag::RequirePasswordSet, column::REQUIRE_PASSWORD_SET),
45 (Tag::DataLabelCritical1, column::CRITICAL1),
46 (Tag::DataLabelCritical2, column::CRITICAL2),
47 (Tag::DataLabelCritical3, column::CRITICAL3),
48 (Tag::DataLabelCritical4, column::CRITICAL4),
49 (Tag::DataLabelNormal1, column::NORMAL1),
50 (Tag::DataLabelNormal2, column::NORMAL2),
51 (Tag::DataLabelNormal3, column::NORMAL3),
52 (Tag::DataLabelNormal4, column::NORMAL4),
53 (Tag::DataLabelNormalLocal1, column::NORMAL_LOCAL1),
54 (Tag::DataLabelNormalLocal2, column::NORMAL_LOCAL2),
55 (Tag::DataLabelNormalLocal3, column::NORMAL_LOCAL3),
56 (Tag::DataLabelNormalLocal4, column::NORMAL_LOCAL4),
57 (Tag::WrapType, column::WRAP_TYPE),
58 ];
59
60 const AAD_ATTR: [&str; 14] = [
61 column::ALIAS,
62 column::OWNER,
63 column::OWNER_TYPE,
64 column::GROUP_ID,
65 column::SYNC_TYPE,
66 column::ACCESSIBILITY,
67 column::REQUIRE_PASSWORD_SET,
68 column::AUTH_TYPE,
69 column::IS_PERSISTENT,
70 column::VERSION,
71 column::CRITICAL1,
72 column::CRITICAL2,
73 column::CRITICAL3,
74 column::CRITICAL4,
75 ];
76
77 pub(crate) const CRITICAL_LABEL_ATTRS: [Tag; 4] =
78 [Tag::DataLabelCritical1, Tag::DataLabelCritical2, Tag::DataLabelCritical3, Tag::DataLabelCritical4];
79
80 pub(crate) const NORMAL_LABEL_ATTRS: [Tag; 4] =
81 [Tag::DataLabelNormal1, Tag::DataLabelNormal2, Tag::DataLabelNormal3, Tag::DataLabelNormal4];
82
83 pub(crate) const NORMAL_LOCAL_LABEL_ATTRS: [Tag; 4] =
84 [Tag::DataLabelNormalLocal1, Tag::DataLabelNormalLocal2, Tag::DataLabelNormalLocal3, Tag::DataLabelNormalLocal4];
85
86 pub(crate) const ACCESS_CONTROL_ATTRS: [Tag; 10] = [
87 Tag::Alias,
88 Tag::Accessibility,
89 Tag::AuthType,
90 Tag::IsPersistent,
91 Tag::SyncType,
92 Tag::RequirePasswordSet,
93 Tag::RequireAttrEncrypted,
94 Tag::GroupId,
95 Tag::WrapType,
96 Tag::UserId,
97 ];
98
99 pub(crate) const ASSET_SYNC_ATTRS: [Tag; 1] = [Tag::OperationType];
100
get_cloumn_name(tag: Tag) -> Option<&'static str>101 pub(crate) fn get_cloumn_name(tag: Tag) -> Option<&'static str> {
102 for (table_tag, table_column) in TAG_COLUMN_TABLE {
103 if table_tag == tag {
104 return Some(table_column);
105 }
106 }
107 None
108 }
109
into_db_map(attrs: &AssetMap) -> DbMap110 pub(crate) fn into_db_map(attrs: &AssetMap) -> DbMap {
111 let mut db_data = DbMap::new();
112 for (attr_tag, attr_value) in attrs.iter() {
113 for (table_tag, table_column) in TAG_COLUMN_TABLE {
114 if *attr_tag == table_tag {
115 db_data.insert(table_column, attr_value.clone());
116 break;
117 }
118 }
119 }
120 db_data
121 }
122
into_asset_map(db_data: &DbMap) -> AssetMap123 pub(crate) fn into_asset_map(db_data: &DbMap) -> AssetMap {
124 let mut map = AssetMap::new();
125 for (column, data) in db_data.iter() {
126 for (table_tag, table_column) in TAG_COLUMN_TABLE {
127 if (*column).eq(table_column) {
128 map.insert(table_tag, data.clone());
129 break;
130 }
131 }
132 }
133 map
134 }
135
add_calling_info(calling_info: &CallingInfo, db_data: &mut DbMap)136 pub(crate) fn add_calling_info(calling_info: &CallingInfo, db_data: &mut DbMap) {
137 db_data.insert(column::OWNER, Value::Bytes(calling_info.owner_info().clone()));
138 db_data.insert(column::OWNER_TYPE, Value::Number(calling_info.owner_type()));
139 if let Some(group) = calling_info.group() {
140 db_data.insert(column::GROUP_ID, Value::Bytes(group));
141 };
142 }
143
build_secret_key(calling: &CallingInfo, attrs: &DbMap) -> Result<SecretKey>144 pub(crate) fn build_secret_key(calling: &CallingInfo, attrs: &DbMap) -> Result<SecretKey> {
145 let auth_type = attrs.get_enum_attr::<AuthType>(&column::AUTH_TYPE)?;
146 let access_type = attrs.get_enum_attr::<Accessibility>(&column::ACCESSIBILITY)?;
147 let require_password_set = attrs.get_bool_attr(&column::REQUIRE_PASSWORD_SET)?;
148 SecretKey::new_without_alias(calling, auth_type, access_type, require_password_set)
149 }
150
build_aad_v1(attrs: &DbMap) -> Vec<u8>151 fn build_aad_v1(attrs: &DbMap) -> Vec<u8> {
152 let mut aad = Vec::new();
153 for column in &AAD_ATTR {
154 match attrs.get(column) {
155 Some(Value::Bytes(bytes)) => aad.extend(bytes),
156 Some(Value::Number(num)) => aad.extend(num.to_le_bytes()),
157 Some(Value::Bool(num)) => aad.push(*num as u8),
158 None => continue,
159 }
160 }
161 aad
162 }
163
to_hex(bytes: &Vec<u8>) -> Result<Vec<u8>>164 fn to_hex(bytes: &Vec<u8>) -> Result<Vec<u8>> {
165 let bytes_len = bytes.len();
166 if bytes_len > MAX_LABEL_SIZE {
167 return log_throw_error!(ErrCode::DataCorrupted, "The data in DB has been tampered with.");
168 }
169
170 let scale_capacity = 2;
171 let mut hex_vec = Vec::with_capacity(bytes_len * scale_capacity);
172 for byte in bytes.iter() {
173 hex_vec.extend(format!("{:02x}", byte).as_bytes());
174 }
175 Ok(hex_vec)
176 }
177
build_aad_v2(attrs: &DbMap) -> Result<Vec<u8>>178 fn build_aad_v2(attrs: &DbMap) -> Result<Vec<u8>> {
179 let mut aad = Vec::new();
180 for column in &AAD_ATTR {
181 aad.extend(format!("{}:", column).as_bytes());
182 match attrs.get(column) {
183 Some(Value::Bytes(bytes)) => aad.extend(to_hex(bytes)?),
184 Some(Value::Number(num)) => aad.extend(num.to_le_bytes()),
185 Some(Value::Bool(num)) => aad.push(*num as u8),
186 None => (),
187 }
188 aad.push(b'_');
189 }
190 Ok(aad)
191 }
192
build_aad(attrs: &DbMap) -> Result<Vec<u8>>193 pub(crate) fn build_aad(attrs: &DbMap) -> Result<Vec<u8>> {
194 let version = attrs.get_num_attr(&column::VERSION)?;
195 if version == DB_DATA_VERSION_V1 {
196 Ok(build_aad_v1(attrs))
197 } else {
198 build_aad_v2(attrs)
199 }
200 }
201
need_upgrade(db_date: &DbMap) -> Result<bool>202 pub(crate) fn need_upgrade(db_date: &DbMap) -> Result<bool> {
203 let version = db_date.get_num_attr(&column::VERSION)?;
204 Ok(version != DB_DATA_VERSION)
205 }
206
inform_asset_ext(calling_info: &CallingInfo, input: &AssetMap)207 pub(crate) fn inform_asset_ext(calling_info: &CallingInfo, input: &AssetMap) {
208 if let Some(Value::Number(operation_type)) = input.get(&Tag::OperationType) {
209 match operation_type {
210 x if *x == OperationType::NeedSync as u32 => {
211 if let Ok(load) = AssetPlugin::get_instance().load_plugin() {
212 let owner_info_str = String::from_utf8_lossy(calling_info.owner_info()).to_string();
213 let owner_info_vec: Vec<_> = owner_info_str.split(OWNER_INFO_SEPARATOR).collect();
214 let caller_name = owner_info_vec[0];
215 let mut params = ExtDbMap::new();
216 params.insert(PARAM_NAME_USER_ID, Value::Number(calling_info.user_id() as u32));
217 params.insert(PARAM_NAME_BUNDLE_NAME, Value::Bytes(caller_name.as_bytes().to_vec()));
218 match load.process_event(EventType::Sync, ¶ms) {
219 Ok(()) => logi!("process sync ext event success."),
220 Err(code) => loge!("process sync ext event failed, code: {}", code),
221 }
222 }
223 },
224 x if *x == OperationType::NeedLogout as u32 => {
225 if let Ok(load) = AssetPlugin::get_instance().load_plugin() {
226 let owner_info_str = String::from_utf8_lossy(calling_info.owner_info()).to_string();
227 let owner_info_vec: Vec<_> = owner_info_str.split(OWNER_INFO_SEPARATOR).collect();
228 let caller_name = owner_info_vec[0];
229 let mut params = ExtDbMap::new();
230 params.insert(PARAM_NAME_USER_ID, Value::Number(calling_info.user_id() as u32));
231 params.insert(PARAM_NAME_BUNDLE_NAME, Value::Bytes(caller_name.as_bytes().to_vec()));
232 match load.process_event(EventType::CleanCloudFlag, ¶ms) {
233 Ok(()) => logi!("process clean cloud flag ext event success."),
234 Err(code) => loge!("process clean cloud flag ext event failed, code: {}", code),
235 }
236 }
237 },
238 x if *x == OperationType::NeedDeleteCloudData as u32 => {
239 if let Ok(load) = AssetPlugin::get_instance().load_plugin() {
240 let mut params = ExtDbMap::new();
241 params.insert(PARAM_NAME_USER_ID, Value::Number(calling_info.user_id() as u32));
242 params.insert(PARAM_NAME_BUNDLE_NAME, Value::Bytes(calling_info.owner_info().clone()));
243 match load.process_event(EventType::DeleteCloudData, ¶ms) {
244 Ok(()) => logi!("process delete cloud data ext event success."),
245 Err(code) => loge!("process delete cloud data ext event failed, code: {}", code),
246 }
247 }
248 },
249 _ => {},
250 }
251 }
252 }
253