final commit for local account enc

Signed-off-by: Cai Xincheng <caixincheng@huawei.com>
Change-Id: I8db226097f9d0453c754b6c21fe9380f287284f0
This commit is contained in:
Cai Xincheng 2024-08-12 14:24:34 +08:00
parent e1b3383f1a
commit fafc5b42e8
20 changed files with 264 additions and 73 deletions

View File

@ -22,6 +22,7 @@ members = [
"services/core_service",
"services/crypto_manager",
"services/db_operator",
"services/db_key_operator",
"test/unittest/inner_api_rust",
"test/unittest/module_test"
]

View File

@ -157,8 +157,8 @@ pub enum Value {
Bool(bool),
/// Asset attribute value, whose data type is number.
Number(u32),
Number(u32),
/// Asset attribute value, whose data type is byte array.
Bytes(Vec<u8>),
}

View File

@ -55,14 +55,14 @@ pub const PARAM_NAME_BUNDLE_NAME: &str = "BundleName";
/// param name for user id
pub const PARAM_NAME_USER_ID: &str = "UserId";
/// param name for user id
/// param name for app index
pub const PARAM_NAME_APP_INDEX: &str = "AppIndex";
/// param name for whether is hap
/// param name for owner type
pub const PARAM_NAME_IS_HAP: &str = "IsHap";
/// param name for whether the attributes of an asset are required to be encrypted.
pub const PARAM_NAME_REQUIRE_ATTR_ENCRYPTED: &str = "RequireAttrEncrypted";
/// param name for owner info
pub const PARAM_NAME_OWNER_INFO: &str = "OwnerInfo";
/// An enumeration representing different plugin types.
#[derive(Default, Hash, PartialEq, Eq, Clone)]
@ -76,35 +76,62 @@ pub enum PluginType {
/// an asset plugin to operate on an asset database.
pub trait IAssetPluginCtx: Any + Sync + Send + std::panic::RefUnwindSafe {
/// Initializes the plugin before usage.
fn init(&mut self, user_id: i32) -> Result<(), u32>;
fn init(&mut self, user_id: u32, owner_type: u32, owner_info: Vec<u8>) -> Result<(), u32>;
/// Adds an asset to the database.
/// Adds an asset to de db.
fn add(&mut self, attributes: &ExtDbMap) -> Result<i32, u32>;
/// Add an asset with replace.
/// Adds an asset to ce cb.
fn ce_add(&mut self, attributes: &ExtDbMap) -> Result<i32, u32>;
/// Adds an asset with replace to de db.
fn replace(&mut self, condition: &ExtDbMap, attributes: &ExtDbMap) -> std::result::Result<(), u32>;
/// Queries the asset database.
/// Adds an asset with replace to ce db.
fn ce_replace(&mut self, condition: &ExtDbMap, attributes: &ExtDbMap) -> std::result::Result<(), u32>;
/// Queries de db.
fn query(&mut self, attributes: &ExtDbMap) -> Result<Vec<ExtDbMap>, u32>;
/// Removes an asset from the database.
/// Queries ce db.
fn ce_query(&mut self, attributes: &ExtDbMap) -> Result<Vec<ExtDbMap>, u32>;
/// Removes an asset from de db.
fn remove(&mut self, attributes: &ExtDbMap) -> Result<i32, u32>;
/// Updates the attributes of an asset in the database.
/// Removes an asset from ce db.
fn ce_remove(&mut self, attributes: &ExtDbMap) -> Result<i32, u32>;
/// Updates the attributes of an asset in de db.
fn update(&mut self, attributes: &ExtDbMap, attrs_to_update: &ExtDbMap) -> Result<i32, u32>;
/// Begins a transaction for the asset database.
/// Updates the attributes of an asset in ce db.
fn ce_update(&mut self, attributes: &ExtDbMap, attrs_to_update: &ExtDbMap) -> Result<i32, u32>;
/// Begins a transaction for de_db.
fn begin_transaction(&mut self) -> Result<(), u32>;
/// Commits a transaction for the asset database.
/// Begins a transaction for the ce db.
fn ce_begin_transaction(&mut self) -> Result<(), u32>;
/// Commits a transaction for de db.
fn commit_transaction(&mut self) -> Result<(), u32>;
/// Rolls back a transaction for the asset database.
/// Commits a transaction for ce db.
fn ce_commit_transaction(&mut self) -> Result<(), u32>;
/// Rolls back a transaction for de db.
fn rollback_transaction(&mut self) -> Result<(), u32>;
/// Returns the storage path for the asset database.
/// Rolls back a transaction for ce db.
fn ce_rollback_transaction(&mut self) -> Result<(), u32>;
/// Returns the storage path for de db.
fn get_storage_path(&self) -> String;
/// Returns the storage path for ce db.
fn ce_get_storage_path(&self) -> String;
/// Increase count
fn increase_count(&mut self);

View File

@ -16,7 +16,6 @@ import("//build/ohos.gni")
ohos_rust_shared_library("asset_service") {
sources = [ "src/lib.rs" ]
deps = [
"../../../../../third_party/rust/crates/rust-openssl/openssl:lib",
"../../etc/init:asset_service.rc",
"../../frameworks/definition:asset_definition",
"../../frameworks/ipc:asset_ipc",
@ -26,6 +25,7 @@ ohos_rust_shared_library("asset_service") {
"../../interfaces/inner_api/rs:asset_sdk_rust",
"../common:asset_common",
"../crypto_manager:asset_crypto_manager",
"../db_key_operator:asset_db_key_operator",
"../db_operator:asset_db_operator",
"../os_dependency:asset_os_dependency",
"../plugin:asset_plugin",

View File

@ -25,10 +25,10 @@ system_ability_fwk = { git = "https://gitee.com/openharmony/systemabilitymgr_saf
hisysevent = { git = "https://gitee.com/openharmony/hiviewdfx_hisysevent.git" }
ipc = { git = "https://gitee.com/openharmony/communication_ipc" }
ylong_runtime = { git = "https://gitee.com/openharmony/commonlibrary_rust_ylong_runtime.git", features = ["full"] }
openssl = { git = "https://gitee.com/openharmony/third_party_rust_rust-openssl.git" }
asset_common = { path = "../common" }
asset_crypto_manager = { path = "../crypto_manager" }
asset_db_key_operator = { path = "../db_key_operator" }
asset_db_operator = { path = "../db_operator" }
asset_definition = { path = "../../frameworks/definition" }
asset_file_operator = { path = "../../frameworks/os_dependency/file" }

View File

@ -28,7 +28,11 @@ use asset_db_operator::{
database::Database,
types::{column, DbMap},
};
use asset_db_key_operator::decrypt_db_key_cipher;
use asset_definition::{log_throw_error, ErrCode, Result, SyncType, Value};
use asset_file_operator::{
read_db_key_cipher, is_ce_db_file_exist, delete_user_de_dir, is_db_key_cipher_file_exist,
};
use asset_log::{loge, logi};
use asset_plugin::asset_plugin::AssetPlugin;
use asset_sdk::plugin_interface::{
@ -36,7 +40,6 @@ use asset_sdk::plugin_interface::{
};
use crate::sys_event::upload_fault_system_event;
use crate::database_key;
const ASSET_DB: &str = "asset.db";
const BACKUP_SUFFIX: &str = ".backup";
@ -63,10 +66,10 @@ fn delete_on_package_removed(calling_info: &CallingInfo, owner: Vec<u8>) -> Resu
check_cond.insert(column::OWNER, Value::Bytes(owner));
let de_db_data_exists = de_db.is_data_exists(&check_cond, false);
if asset_file_operator::is_ce_db_file_exist(calling_info.user_id()).is_ok() {
if is_ce_db_file_exist(calling_info.user_id()).is_ok() {
// Delete non-persistent data in ce db if ce db file exists.
let db_key_cipher = asset_file_operator::read_db_key_cipher(calling_info.user_id())?;
let db_key = database_key::decrypt_db_key_cipher(calling_info, &db_key_cipher)?;
let db_key_cipher = read_db_key_cipher(calling_info.user_id())?;
let db_key = decrypt_db_key_cipher(calling_info, &db_key_cipher)?;
let mut ce_db = Database::build(calling_info.user_id(), Some(&db_key))?;
let _ = ce_db.delete_datas(&delete_cond, Some(&reverse_condition), false)?;
@ -157,7 +160,7 @@ pub(crate) extern "C" fn on_package_removed(
extern "C" fn delete_dir_by_user(user_id: i32) {
let _counter_user = AutoCounter::new();
let _ = asset_file_operator::delete_user_de_dir(user_id);
let _ = delete_user_de_dir(user_id);
}
extern "C" fn delete_crypto_need_unlock() {
@ -240,7 +243,7 @@ fn backup_de_db_if_accessible(entry: &DirEntry, user_id: i32) -> Result<()> {
}
fn backup_ce_db_if_exists(user_id: i32) -> Result<()> {
asset_file_operator::is_ce_db_file_exist(user_id)?;
is_ce_db_file_exist(user_id)?;
let from_path = format!("{}/{}/asset_service/{}", CE_ROOT_PATH, user_id, ASSET_DB);
let backup_path = format!("{}{}", from_path, BACKUP_SUFFIX);
fs::copy(from_path, backup_path)?;
@ -249,7 +252,7 @@ fn backup_ce_db_if_exists(user_id: i32) -> Result<()> {
}
fn backup_db_key_cipher_if_exists(user_id: i32) -> Result<()> {
match asset_file_operator::is_db_key_cipher_file_exist(user_id) {
match is_db_key_cipher_file_exist(user_id) {
Ok(true) => {
let from_path = format!("{}/{}/asset_service/db_key", CE_ROOT_PATH, user_id);
let backup_path = format!("{}{}", from_path, BACKUP_SUFFIX);
@ -279,7 +282,7 @@ fn backup_all_db(start_time: &Instant) -> Result<()> {
}
}
// Backup all ce db and db key cipher if exists. (todo?: backup ce db if accessible)
// Backup all ce db and db key cipher if exists. (todo1?: backup ce db if accessible. todo2?: do not backup db key cipher.)
unsafe {
/* Temporarily allocate at least 256 spaces for user ids.
If the number of user ids exceeds 256, this method(with_capacity) will automatically allocate more spaces.*/

View File

@ -18,6 +18,7 @@
use std::collections::HashMap;
use asset_log::{loge, logi};
use asset_file_operator::delete_user_de_dir;
use system_ability_fwk::cxx_share::SystemAbilityOnDemandReason;
use crate::common_event::listener;
@ -81,7 +82,7 @@ pub(crate) fn handle_common_event(reason: SystemAbilityOnDemandReason) {
handle_package_removed(&want, true);
} else if reason_name == "usual.event.USER_REMOVED" {
logi!("on_start by user remove");
let _ = asset_file_operator::delete_user_de_dir(reason.extra_data.code);
let _ = delete_user_de_dir(reason.extra_data.code);
} else if reason_name == "usual.event.CHARGING" {
listener::backup_db();
} else if reason_name == "COMMON_EVENT_RESTORE_START" {

View File

@ -27,6 +27,7 @@ use ylong_runtime::{builder::RuntimeBuilder, time::sleep};
use asset_common::{CallingInfo, Counter};
use asset_crypto_manager::crypto_manager::CryptoManager;
use asset_definition::{log_throw_error, AssetMap, ErrCode, Result};
use asset_file_operator::create_user_de_dir;
use asset_ipc::SA_ID;
use asset_log::{loge, logi};
use asset_plugin::asset_plugin::{AssetContext, AssetPlugin};
@ -37,7 +38,6 @@ mod stub;
mod sys_event;
mod trace_scope;
mod unload_handler;
mod database_key;
use sys_event::upload_system_event;
use trace_scope::TraceScope;
@ -107,7 +107,7 @@ fn start_service(handler: Handler) -> Result<()> {
let asset_plugin = AssetPlugin::get_instance();
match asset_plugin.load_plugin() {
Ok(loader) => {
let _tr = loader.init(Box::new(AssetContext { data_base: None }));
let _tr = loader.init(Box::new(AssetContext { de_db: None, ce_db: None }));
logi!("load plugin success.");
},
Err(_) => loge!("load plugin failed."),
@ -144,7 +144,7 @@ macro_rules! execute {
let start = Instant::now();
let _trace = TraceScope::trace(func_name);
// Create de database directory if not exists.
asset_file_operator::create_user_de_dir($calling_info.user_id())?;
create_user_de_dir($calling_info.user_id())?;
upload_system_event($func($calling_info, $($args),+), $calling_info, start, func_name)
}};
}

View File

@ -29,7 +29,9 @@ use asset_definition::{
};
use asset_log::{loge, logi};
use asset_plugin::asset_plugin::AssetPlugin;
use asset_sdk::plugin_interface::{EventType, ExtDbMap, PARAM_NAME_BUNDLE_NAME, PARAM_NAME_USER_ID};
use asset_sdk::plugin_interface::{
EventType, ExtDbMap, PARAM_NAME_BUNDLE_NAME, PARAM_NAME_USER_ID, PARAM_NAME_IS_HAP, PARAM_NAME_OWNER_INFO
};
const TAG_COLUMN_TABLE: [(Tag, &str); 20] = [
(Tag::Secret, column::SECRET),
@ -206,6 +208,8 @@ pub(crate) fn inform_asset_ext(calling_info: &CallingInfo, input: &AssetMap) {
let caller_name = owner_info_vec[0];
let mut params = ExtDbMap::new();
params.insert(PARAM_NAME_USER_ID, Value::Number(calling_info.user_id() as u32));
params.insert(PARAM_NAME_IS_HAP, Value::Number(calling_info.owner_type()));
params.insert(PARAM_NAME_OWNER_INFO, Value::Bytes(calling_info.owner_info().to_vec()));
params.insert(PARAM_NAME_BUNDLE_NAME, Value::Bytes(caller_name.as_bytes().to_vec()));
match load.process_event(EventType::Sync, &params) {
Ok(()) => logi!("process sync ext event success."),

View File

@ -23,6 +23,9 @@ use asset_db_operator::{
database::Database,
types::{column, DbMap, DB_DATA_VERSION},
};
use asset_db_key_operator::{
create_db_instance, generate_secret_key_if_needed,
};
use asset_definition::{
log_throw_error, Accessibility, AssetMap, AuthType, ConflictResolution, ErrCode, Extension, LocalStatus, Result,
SyncStatus, SyncType, Tag, Value,
@ -30,11 +33,10 @@ use asset_definition::{
use asset_utils::time;
use crate::operations::common;
use crate::database_key;
fn encrypt_secret(calling_info: &CallingInfo, db_data: &mut DbMap) -> Result<()> {
let secret_key = common::build_secret_key(calling_info, db_data)?;
database_key::generate_secret_key_if_needed(&secret_key)?;
generate_secret_key_if_needed(&secret_key)?;
let secret = db_data.get_bytes_attr(&column::SECRET)?;
let cipher = Crypto::encrypt(&secret_key, secret, &common::build_aad(db_data)?)?;
@ -156,7 +158,7 @@ fn local_add(attributes: &AssetMap, calling_info: &CallingInfo) -> Result<()> {
let query = get_query_condition(calling_info, attributes)?;
let mut db = database_key::create_db_instance(attributes, calling_info)?;
let mut db = create_db_instance(attributes, calling_info)?;
if db.is_data_exists(&query, false)? {
resolve_conflict(calling_info, &mut db, attributes, &query, &mut db_data)?;

View File

@ -18,10 +18,10 @@
use asset_common::CallingInfo;
use asset_crypto_manager::{crypto::Crypto, crypto_manager::CryptoManager, secret_key::SecretKey};
use asset_db_operator::types::{column, DbMap};
use asset_db_key_operator::create_db_instance;
use asset_definition::{log_throw_error, Accessibility, AssetMap, AuthType, ErrCode, Extension, Result, Tag, Value};
use crate::operations::common;
use crate::database_key;
const OPTIONAL_ATTRS: [Tag; 1] = [Tag::AuthValidityPeriod];
const DEFAULT_AUTH_VALIDITY_IN_SECS: u32 = 60;
@ -46,7 +46,7 @@ fn check_arguments(attributes: &AssetMap) -> Result<()> {
}
fn query_key_attrs(calling_info: &CallingInfo, db_data: &DbMap, attrs: &AssetMap) -> Result<(Accessibility, bool)> {
let mut db = database_key::create_db_instance(attrs, calling_info)?;
let mut db = create_db_instance(attrs, calling_info)?;
let results = db.query_datas(
&vec![column::ACCESSIBILITY, column::REQUIRE_PASSWORD_SET],
db_data,

View File

@ -23,12 +23,12 @@ use asset_db_operator::{
database::Database,
types::{column, DbMap, QueryOptions, DB_DATA_VERSION},
};
use asset_db_key_operator::create_db_instance;
use asset_definition::{
log_throw_error, throw_error, AssetMap, AuthType, ErrCode, Extension, Result, ReturnType, Tag, Value,
};
use crate::operations::common;
use crate::database_key;
fn into_asset_maps(db_results: &Vec<DbMap>) -> Result<Vec<AssetMap>> {
let mut map_set = Vec::new();
@ -87,7 +87,7 @@ fn exec_crypto(calling_info: &CallingInfo, query: &AssetMap, db_data: &mut DbMap
}
fn query_all(calling_info: &CallingInfo, db_data: &mut DbMap, query: &AssetMap) -> Result<Vec<AssetMap>> {
let mut db = database_key::create_db_instance(query, calling_info)?;
let mut db = create_db_instance(query, calling_info)?;
let mut results = db.query_datas(&vec![], db_data, None, true)?;
match results.len() {
0 => throw_error!(ErrCode::NotFound, "[FATAL]The data to be queried does not exist."),
@ -141,7 +141,7 @@ fn get_query_options(attrs: &AssetMap) -> QueryOptions {
}
pub(crate) fn query_attrs(calling_info: &CallingInfo, db_data: &DbMap, attrs: &AssetMap) -> Result<Vec<AssetMap>> {
let mut db = database_key::create_db_instance(attrs, calling_info)?;
let mut db = create_db_instance(attrs, calling_info)?;
let mut results = db.query_datas(
&vec![],
db_data,

View File

@ -17,12 +17,12 @@
use asset_common::CallingInfo;
use asset_db_operator::types::{column, DbMap};
use asset_db_key_operator::create_db_instance;
use asset_definition::{log_throw_error, AssetMap, ErrCode, Result, SyncStatus, SyncType, Value};
use asset_log::logi;
use asset_utils::time;
use crate::operations::common;
use crate::database_key;
fn add_system_attrs(db_data: &mut DbMap) -> Result<()> {
let time = time::system_time_in_millis()?;
@ -55,7 +55,7 @@ pub(crate) fn remove(calling_info: &CallingInfo, query: &AssetMap) -> Result<()>
add_system_attrs(&mut update_db_data)?;
add_normal_attrs(&mut update_db_data);
let mut db = database_key::create_db_instance(query, calling_info)?;
let mut db = create_db_instance(query, calling_info)?;
let results = db.query_datas(&vec![], &db_data, None, true)?;
if results.is_empty() {
return log_throw_error!(ErrCode::NotFound, "[FATAL]The data to be deleted does not exist.");

View File

@ -18,11 +18,11 @@
use asset_common::CallingInfo;
use asset_crypto_manager::crypto::Crypto;
use asset_db_operator::types::{column, DbMap, DB_DATA_VERSION};
use asset_db_key_operator::create_db_instance;
use asset_definition::{log_throw_error, AssetMap, ErrCode, Extension, LocalStatus, Result, SyncStatus, Tag, Value};
use asset_utils::time;
use crate::operations::common;
use crate::database_key;
fn encrypt(calling_info: &CallingInfo, db_data: &DbMap) -> Result<Vec<u8>> {
let secret_key = common::build_secret_key(calling_info, db_data)?;
@ -95,7 +95,7 @@ pub(crate) fn update(calling_info: &CallingInfo, query: &AssetMap, update: &Asse
add_system_attrs(update, &mut update_db_data)?;
add_normal_attrs(&mut update_db_data);
let mut db = database_key::create_db_instance(query, calling_info)?;
let mut db = create_db_instance(query, calling_info)?;
let results = db.query_datas(&vec![], &query_db_data, None, true)?;
if results.is_empty() {
return log_throw_error!(ErrCode::NotFound, "[FATAL]The asset to update is not found.");

View File

@ -0,0 +1,32 @@
# Copyright (c) 2024 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_rust_static_library("asset_db_key_operator") {
sources = [ "src/lib.rs" ]
deps = [
"../../../../../third_party/rust/crates/rust-openssl/openssl:lib",
"../../frameworks/definition:asset_definition",
"../../frameworks/os_dependency/file:asset_file_operator",
"../../frameworks/os_dependency/log:asset_log",
"../common:asset_common",
"../crypto_manager:asset_crypto_manager",
"../db_operator:asset_db_operator",
]
crate_name = "asset_db_key_operator"
crate_type = "rlib"
subsystem_name = "security"
part_name = "asset"
}

View File

@ -0,0 +1,29 @@
# Copyright (c) 2024 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.
[package]
name = "asset_db_key_operator"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
openssl = { git = "https://gitee.com/openharmony/third_party_rust_rust-openssl.git" }
asset_common = { path = "../common" }
asset_crypto_manager = { path = "../crypto_manager" }
asset_db_operator = { path = "../db_operator" }
asset_definition = { path = "../../frameworks/definition" }
asset_file_operator = { path = "../../frameworks/os_dependency/file" }
asset_log = { path = "../../frameworks/os_dependency/log" }

View File

@ -25,6 +25,9 @@ use asset_db_operator::database::Database;
use asset_definition::{
Accessibility, AssetMap, AuthType, Result, Tag, Value
};
use asset_file_operator::{
is_db_key_cipher_file_exist, read_db_key_cipher, write_db_key_cipher,
};
use asset_log::logi;
fn build_db_key_secret_key(calling_info: &CallingInfo) -> Result<SecretKey> {
@ -36,7 +39,8 @@ fn build_db_key_secret_key(calling_info: &CallingInfo) -> Result<SecretKey> {
Ok(SecretKey::new(calling_info, auth_type, access_type, require_password_set, Some(alias)))
}
pub(crate) fn decrypt_db_key_cipher(calling_info: &CallingInfo, db_key_cipher: &Vec<u8>) -> Result<Vec<u8>> {
/// Decrypt db key cipher.
pub fn decrypt_db_key_cipher(calling_info: &CallingInfo, db_key_cipher: &Vec<u8>) -> Result<Vec<u8>> {
let secret_key = build_db_key_secret_key(calling_info)?;
let aad: Vec<u8> = "trivial_aad_for_db_key".as_bytes().to_vec();
let db_key = Crypto::decrypt(&secret_key, db_key_cipher, &aad)?;
@ -54,7 +58,8 @@ fn generate_db_key() -> Result<Vec<u8>> {
static GEN_KEY_MUTEX: Mutex<()> = Mutex::new(());
pub(crate) fn generate_secret_key_if_needed(secret_key: &SecretKey) -> Result<()> {
/// Generate secret key if it does not exist.
pub fn generate_secret_key_if_needed(secret_key: &SecretKey) -> Result<()> {
match secret_key.exists() {
Ok(true) => Ok(()),
Ok(false) => {
@ -81,25 +86,27 @@ fn encrypt_db_key(calling_info: &CallingInfo, db_key: &Vec<u8>) -> Result<Vec<u8
Ok(db_key_cipher)
}
fn get_db_key(calling_info: &CallingInfo) -> Result<Vec<u8>>
/// Read db key cipher and decrypt if the db key cipher file exists, generate db_key if not.
pub fn get_db_key(calling_info: &CallingInfo) -> Result<Vec<u8>>
{
match asset_file_operator::is_db_key_cipher_file_exist(calling_info.user_id()) {
match is_db_key_cipher_file_exist(calling_info.user_id()) {
Ok(true) => {
let db_key_cipher = asset_file_operator::read_db_key_cipher(calling_info.user_id())?;
let db_key_cipher = read_db_key_cipher(calling_info.user_id())?;
let db_key = decrypt_db_key_cipher(calling_info, &db_key_cipher)?;
Ok(db_key)
},
Ok(false) => {
let db_key = generate_db_key()?;
let db_key_cipher = encrypt_db_key(calling_info, &db_key)?;
asset_file_operator::write_db_key_cipher(calling_info.user_id(), &db_key_cipher)?;
write_db_key_cipher(calling_info.user_id(), &db_key_cipher)?;
Ok(db_key)
},
Err(e) => Err(e),
}
}
pub(crate) fn create_db_instance(attributes: &AssetMap, calling_info: &CallingInfo) -> Result<Database> {
/// Create de db instance if the value of tag "RequireAttrEncrypted" is set to false, Create ce db instance if true.
pub fn create_db_instance(attributes: &AssetMap, calling_info: &CallingInfo) -> Result<Database> {
match attributes.get(&Tag::RequireAttrEncrypted) {
Some(Value::Bool(true)) => {
let db_key = get_db_key(calling_info)?;

View File

@ -22,6 +22,7 @@ ohos_rust_static_library("asset_plugin") {
"../../frameworks/utils:asset_utils",
"../../interfaces/inner_api/rs:asset_sdk_rust",
"../common:asset_common",
"../db_key_operator:asset_db_key_operator",
"../db_operator:asset_db_operator",
"//third_party/rust/crates/libloading:lib",
]

View File

@ -23,5 +23,6 @@ asset_common = { path = "../common" }
asset_definition = { path = "../../frameworks/definition" }
asset_log = { path = "../../frameworks/os_dependency/log" }
asset_sdk = { path = "../../interfaces/inner_api/rs" }
asset_db_key_operator = { path = "../db_key_operator" }
asset_db_operator = { path = "../db_operator" }
asset_file_operator = { path = "../../frameworks/os_dependency/file" }

View File

@ -13,9 +13,11 @@
* limitations under the License.
*/
use asset_common::Counter;
use asset_common::{CallingInfo, Counter, OwnerType};
use asset_db_operator::database::{get_path, Database};
use asset_db_key_operator::get_db_key;
use asset_definition::{log_throw_error, ErrCode, Result};
use asset_file_operator::create_user_de_dir;
use asset_log::{loge, logi};
use asset_sdk::plugin_interface::{ExtDbMap, IAssetPlugin, IAssetPluginCtx};
use std::{
@ -97,90 +99,171 @@ impl AssetPlugin {
/// The asset_ext plugin context.
#[repr(C)]
pub struct AssetContext {
/// The asset database instance.
pub data_base: Option<Database>,
/// The asset de db instance.
pub de_db: Option<Database>,
/// The asset ce db instance.
pub ce_db: Option<Database>,
}
#[allow(dead_code)]
impl IAssetPluginCtx for AssetContext {
/// Initializes the plugin before usage.
fn init(&mut self, user_id: i32) -> std::result::Result<(), u32> {
// Create database directory if not exists.
asset_file_operator::create_user_de_dir(user_id).map_err(|e| e.code as u32)?;
fn init(&mut self, user_id: u32, owner_type: u32, owner_info: Vec<u8>) -> std::result::Result<(), u32> {
create_user_de_dir(user_id as i32).map_err(|e| e.code as u32)?;
let de_db = Database::build(user_id as i32, None).map_err(|e| e.code as u32)?;
self.de_db = Some(de_db);
let owner_type = match owner_type {
0 => OwnerType::Hap,
1 => OwnerType::Native,
_ => return Err(ErrCode::InvalidArgument as u32),
};
let calling_info = CallingInfo::new(user_id as i32, owner_type, owner_info);
let db_key = get_db_key(&calling_info).map_err(|e| e.code as u32)?;
let ce_db = Database::build(calling_info.user_id(), Some(&db_key)).map_err(|e| e.code as u32)?;
self.ce_db = Some(ce_db);
let db = Database::build(user_id, None).map_err(|e| e.code as u32)?;
self.data_base = Some(db);
Ok(())
}
/// Adds an asset to the database.
/// Adds an asset to de db.
fn add(&mut self, attributes: &ExtDbMap) -> std::result::Result<i32, u32> {
self.data_base
self.de_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.insert_datas(attributes)
.map_err(|e| e.code as u32)
}
/// Adds an asset to ce db.
fn ce_add(&mut self, attributes: &ExtDbMap) -> std::result::Result<i32, u32> {
self.ce_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.insert_datas(attributes)
.map_err(|e| e.code as u32)
}
/// Adds an asset with replace to de db.
fn replace(&mut self, condition: &ExtDbMap, attributes: &ExtDbMap) -> std::result::Result<(), u32> {
self.data_base
self.de_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.replace_datas(condition, false, attributes)
.map_err(|e| e.code as u32)
}
/// Queries the asset database.
/// Adds an asset with replace to ce db.
fn ce_replace(&mut self, condition: &ExtDbMap, attributes: &ExtDbMap) -> std::result::Result<(), u32> {
self.ce_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.replace_datas(condition, false, attributes)
.map_err(|e| e.code as u32)
}
/// Queries de db.
fn query(&mut self, attributes: &ExtDbMap) -> std::result::Result<Vec<ExtDbMap>, u32> {
self.data_base
self.de_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.query_datas(&vec![], attributes, None, false)
.map_err(|e| e.code as u32)
}
/// Removes an asset from the database.
/// Queries ce db.
fn ce_query(&mut self, attributes: &ExtDbMap) -> std::result::Result<Vec<ExtDbMap>, u32> {
self.ce_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.query_datas(&vec![], attributes, None, false)
.map_err(|e| e.code as u32)
}
/// Removes an asset from de db.
fn remove(&mut self, attributes: &ExtDbMap) -> std::result::Result<i32, u32> {
self.data_base
self.de_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.delete_datas(attributes, None, false)
.map_err(|e| e.code as u32)
}
/// Updates the attributes of an asset in the database.
/// Removes an asset from ce db.
fn ce_remove(&mut self, attributes: &ExtDbMap) -> std::result::Result<i32, u32> {
self.ce_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.delete_datas(attributes, None, false)
.map_err(|e| e.code as u32)
}
/// Updates the attributes of an asset in de db.
fn update(&mut self, attributes: &ExtDbMap, attrs_to_update: &ExtDbMap) -> std::result::Result<i32, u32> {
self.data_base
self.de_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.update_datas(attributes, false, attrs_to_update)
.map_err(|e| e.code as u32)
}
/// Begins a transaction for the asset database.
/// Updates the attributes of an asset in ce db.
fn ce_update(&mut self, attributes: &ExtDbMap, attrs_to_update: &ExtDbMap) -> std::result::Result<i32, u32> {
self.ce_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.update_datas(attributes, false, attrs_to_update)
.map_err(|e| e.code as u32)
}
/// Begins a transaction for de db.
fn begin_transaction(&mut self) -> std::result::Result<(), u32> {
self.data_base
self.de_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.exec("begin immediate")
.map_err(|e| e.code as u32)
}
/// Commits a transaction for the asset database.
/// Begins a transaction for ce db.
fn ce_begin_transaction(&mut self) -> std::result::Result<(), u32> {
self.ce_db
.as_mut()
.ok_or(ErrCode::InvalidArgument as u32)?
.exec("begin immediate")
.map_err(|e| e.code as u32)
}
/// Commits a transaction for de db.
fn commit_transaction(&mut self) -> std::result::Result<(), u32> {
self.data_base.as_mut().ok_or(ErrCode::InvalidArgument as u32)?.exec("commit").map_err(|e| e.code as u32)
self.de_db.as_mut().ok_or(ErrCode::InvalidArgument as u32)?.exec("commit").map_err(|e| e.code as u32)
}
/// Rolls back a transaction for the asset database.
/// Commits a transaction for ce db.
fn ce_commit_transaction(&mut self) -> std::result::Result<(), u32> {
self.ce_db.as_mut().ok_or(ErrCode::InvalidArgument as u32)?.exec("commit").map_err(|e| e.code as u32)
}
/// Rolls back a transaction for de db.
fn rollback_transaction(&mut self) -> std::result::Result<(), u32> {
self.data_base.as_mut().ok_or(ErrCode::InvalidArgument as u32)?.exec("rollback").map_err(|e| e.code as u32)
self.de_db.as_mut().ok_or(ErrCode::InvalidArgument as u32)?.exec("rollback").map_err(|e| e.code as u32)
}
/// Returns the storage path for the asset database.
/// Rolls back a transaction for ce db.
fn ce_rollback_transaction(&mut self) -> std::result::Result<(), u32> {
self.ce_db.as_mut().ok_or(ErrCode::InvalidArgument as u32)?.exec("rollback").map_err(|e| e.code as u32)
}
/// Returns the storage path for de db.
fn get_storage_path(&self) -> String {
get_path()
}
/// Returns the storage path for ce db.
fn ce_get_storage_path(&self) -> String {
get_path()
}
/// Increase count
fn increase_count(&mut self) {
let counter = Counter::get_instance();