modify error code

Change-Id: Ifbb8b9693e31f075b67aad875045fa9b39e06e8a

Match-id-85d972ce09dcd2c44b089079e74231ae3d1125fb
This commit is contained in:
authName 2023-11-22 00:52:03 +08:00 committed by userName
parent 00cc3ff8cb
commit 04cc253df6
31 changed files with 476 additions and 423 deletions

View File

@ -71,8 +71,8 @@ impl_tag_trait! {
/// A tag whose value is a 32-bit unsigned integer indicating the type of Asset synchronization.
SyncType = DataType::Number as isize | 0x10,
/// A tag whose value is a 32-bit unsigned integer indicating when to delete Asset.
DeleteType = DataType::Number as isize | 0x11,
/// A tag whose value is a bool indicating whether Asset is stored persistently.
IsPersistent = DataType::Bool as isize | 0x11,
/// A tag whose value is a byte array indicating the first user-defined Asset data label (not allow to update).
DataLabelCritical1 = DataType::Bytes as isize | 0x20,
@ -169,47 +169,41 @@ impl_enum_trait! {
/// The error code indicates that the access to Asset is denied.
AccessDenied = 24000004,
/// The error code indicates that the authentication token has expired.
AuthTokenExpired = 24000005,
/// The error code indicates that the screen lock status mismatches.
StatusMismatch = 24000006,
StatusMismatch = 24000005,
/// The error code indicates insufficient memory.
OutOfMemory = 24000007,
OutOfMemory = 24000006,
/// The error code indicates that the Asset or encryption key is corrupted.
DataCorrupted = 24000008,
/// The error code indicates that the ipc communication is abnormal.
IpcError = 24000009,
/// The error code indicates that the Asset is corrupted.
DataCorrupted = 24000007,
/// The error code indicates that the database operation is failed.
DatabaseError = 24000010,
DatabaseError = 24000008,
/// The error code indicates that the cryptography operation is failed.
CryptoError = 24000009,
/// The error code indicates that the ipc communication is abnormal.
IpcError = 24000010,
/// The error code indicates that the operation of calling bundle manager service is failed.
BmsError = 24000011,
/// The error code indicates that the cryptography operation is failed.
CryptoError = 24000012,
/// The error code indicates that the operation of calling OS account service is failed.
AccountError = 24000013,
/// The error code indicates that the operation of calling common event service is failed.
CommonEventError = 24000014,
AccountError = 24000012,
/// The error code indicates that the operation of calling access token service is failed.
AccessTokenError = 24000015,
AccessTokenError = 24000013,
/// The error code indicates that the operation of file is failed.
FileOperationError = 24000016,
FileOperationError = 24000014,
/// The error code indicates that the operation of getting system time failed.
GetSystemTimeError = 24000017,
GetSystemTimeError = 24000015,
/// The error code indicates that the amount of map element or other limited quotas exceed the limit.
LimitExceeded = 24000018,
LimitExceeded = 24000016,
}
}
@ -280,19 +274,6 @@ impl_enum_trait! {
}
}
impl_enum_trait! {
/// An enum type indicates the type of when to delete Asset.
#[derive(Debug)]
#[derive(PartialEq, Eq)]
pub enum DeleteType {
/// The Asset is deleted when the user space it belongs to is removed.
WhenUserRemoved = 1 << 0,
/// The Asset is deleted when the package it belongs to is removed.
WhenPackageRemoved = 1 << 1,
}
}
impl_enum_trait! {
/// An enum type indicates the strategy for conflict resolution when handling duplicated Asset alias.
#[derive(Default)]

View File

@ -74,7 +74,7 @@ pub trait IAsset: ipc_rust::IRemoteBroker {
/// serialize the map to parcel
pub fn serialize_map(map: &AssetMap, parcel: &mut BorrowedMsgParcel) -> Result<()> {
if map.len() as u32 > MAX_MAP_CAPACITY {
return log_throw_error!(ErrCode::LimitExceeded, "[FALTAL][IPC]The map size exceeds the limit.");
return log_throw_error!(ErrCode::InvalidArgument, "[FALTAL][IPC]The map size exceeds the limit.");
}
parcel.write(&(map.len() as u32)).map_err(ipc_err_handle)?;
for (&tag, value) in map.iter() {
@ -100,7 +100,7 @@ pub fn serialize_map(map: &AssetMap, parcel: &mut BorrowedMsgParcel) -> Result<(
pub fn deserialize_map(parcel: &BorrowedMsgParcel) -> Result<AssetMap> {
let len = parcel.read::<u32>().map_err(ipc_err_handle)?;
if len > MAX_MAP_CAPACITY {
return log_throw_error!(ErrCode::LimitExceeded, "[FATAL][IPC]The map size exceeds the limit.");
return log_throw_error!(ErrCode::InvalidArgument, "[FATAL][IPC]The map size exceeds the limit.");
}
let mut map = AssetMap::with_capacity(len as usize);
for _ in 0..len {
@ -127,7 +127,7 @@ pub fn deserialize_map(parcel: &BorrowedMsgParcel) -> Result<AssetMap> {
/// Serialize the collection of map to parcel.
pub fn serialize_maps(vec: &Vec<AssetMap>, parcel: &mut BorrowedMsgParcel) -> Result<()> {
if vec.len() as u32 > MAX_VEC_CAPACITY {
return log_throw_error!(ErrCode::LimitExceeded, "[FATAL][IPC]The vector size exceeds the limit.");
return log_throw_error!(ErrCode::InvalidArgument, "[FATAL][IPC]The vector size exceeds the limit.");
}
parcel.write::<u32>(&(vec.len() as u32)).map_err(ipc_err_handle)?;
for map in vec.iter() {
@ -140,7 +140,7 @@ pub fn serialize_maps(vec: &Vec<AssetMap>, parcel: &mut BorrowedMsgParcel) -> Re
pub fn deserialize_maps(parcel: &BorrowedMsgParcel) -> Result<Vec<AssetMap>> {
let len = parcel.read::<u32>().map_err(ipc_err_handle)?;
if len > MAX_VEC_CAPACITY {
return log_throw_error!(ErrCode::LimitExceeded, "[FATAL][IPC]The vector size exceeds the limit.");
return log_throw_error!(ErrCode::InvalidArgument, "[FATAL][IPC]The vector size exceeds the limit.");
}
let mut res_vec = Vec::with_capacity(len as usize);
for _i in 0..len {

View File

@ -27,8 +27,24 @@ declare namespace asset {
/**
* Add an Asset.
*
* @permission ohos.permission.STORE_PERSISTENT_DATA
* @param { AssetMap } attributes - a map object containing attributes of the Asset to be added.
* @param { AsyncCallback<void> } callback - the callback function for add operation.
* @throws { BusinessError } 201 - Permission denied.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000003 - Data already exists.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000011 - Key manager is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @throws { BusinessError } 24000014 - File operation failed.
* @throws { BusinessError } 24000015 - Get system time failed.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -37,8 +53,24 @@ declare namespace asset {
/**
* Add an Asset.
*
* @permission ohos.permission.STORE_PERSISTENT_DATA
* @param { AssetMap } attributes - a map object containing attributes of the Asset to be added.
* @returns { Promise<void> } the promise object returned by the function.
* @throws { BusinessError } 201 - Permission denied.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000003 - Data already exists.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @throws { BusinessError } 24000014 - File operation failed.
* @throws { BusinessError } 24000015 - Get system time failed.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -49,6 +81,17 @@ declare namespace asset {
*
* @param { AssetMap } query - a map object containing attributes of the Asset to be removed.
* @param { AsyncCallback<void> } callback - the callback function for remove operation.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000011 - Algorithm operation failed.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -59,6 +102,16 @@ declare namespace asset {
*
* @param { AssetMap } query - a map object containing attributes of the Asset to be removed.
* @returns { Promise<void> } the promise object returned by the function.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -70,6 +123,19 @@ declare namespace asset {
* @param { AssetMap } query - a map object containing attributes of the Asset to be updated.
* @param { AssetMap } attributesToUpdate - a map object containing attributes with new values.
* @param { AsyncCallback<void> } callback - the callback function for update operation.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @throws { BusinessError } 24000015 - Get system time failed.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -81,6 +147,19 @@ declare namespace asset {
* @param { AssetMap } query - a map object containing attributes of the Asset to be updated.
* @param { AssetMap } attributesToUpdate - a map object containing attributes with new values.
* @returns { Promise<void> } the promise object returned by the function.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @throws { BusinessError } 24000015 - Get system time failed.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -91,6 +170,20 @@ declare namespace asset {
*
* @param { AssetMap } query - a map object containing attributes of the Asset to be queried.
* @param { AsyncCallback<Uint8Array> } callback - the callback function for pre-query operation.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 801 - Capability not supported.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @throws { BusinessError } 24000016 - Capacity exceeds the limit.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -101,6 +194,20 @@ declare namespace asset {
*
* @param { AssetMap } query - a map object containing attributes of the Asset to be queried.
* @returns { Promise<Uint8Array> } the promise object returned by the function.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 801 - Capability not supported.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @throws { BusinessError } 24000016 - Capacity exceeds the limit.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -111,6 +218,20 @@ declare namespace asset {
*
* @param { AssetMap } query - a map object containing attributes of the Asset to be queried.
* @param { AsyncCallback<Array<AssetMap>> } callback - the callback function for query operation.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 801 - Capability not supported.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000004 - Access denied.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -121,6 +242,20 @@ declare namespace asset {
*
* @param { AssetMap } query - a map object containing attributes of the Asset to be queried.
* @returns { Promise<Array<AssetMap>> } the promise object returned by the function.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 801 - Capability not supported.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000002 - Data not found.
* @throws { BusinessError } 24000004 - Access denied.
* @throws { BusinessError } 24000005 - Device status mismatch.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000007 - Data corrupted.
* @throws { BusinessError } 24000008 - Database operation failed.
* @throws { BusinessError } 24000009 - Key management service is abnormal.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -131,6 +266,13 @@ declare namespace asset {
*
* @param { AssetMap } handle - a map object contains the handle returned by {@link preQuery}.
* @param { AsyncCallback<void> } callback - the callback function for post-query operation.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -141,6 +283,13 @@ declare namespace asset {
*
* @param { AssetMap } handle - a map object contains the handle returned by {@link preQuery}.
* @returns { Promise<void> } the promise object returned by the function.
* @throws { BusinessError } 401 - Invalid argument.
* @throws { BusinessError } 24000001 - Service unavailable.
* @throws { BusinessError } 24000006 - Out of memory.
* @throws { BusinessError } 24000010 - IPC communication is abnormal.
* @throws { BusinessError } 24000011 - Bundle framework is abnormal.
* @throws { BusinessError } 24000012 - Account manager is abnormal.
* @throws { BusinessError } 24000013 - Access token manager is abnormal.
* @syscap SystemCapability.Security.Asset
* @since 11
*/
@ -248,30 +397,6 @@ declare namespace asset {
TRUSTED_DEVICE = 1 << 1,
}
/**
* An enum type indicates the type of when to delete Asset.
*
* @enum { number }
* @syscap SystemCapability.Security.Asset
* @since 11
*/
enum DeleteType {
/**
* The Asset is deleted when the user space it belongs to is removed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
WHEN_USER_REMOVED = 1 << 0,
/**
* The Asset is deleted when the package it belongs to is removed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
WHEN_PACKAGE_REMOVED = 1 << 1,
}
/**
* An enum type indicates the strategy for conflict resolution when handling duplicated Asset alias.
*
@ -381,7 +506,7 @@ declare namespace asset {
*/
ACCESSIBILITY = TagType.NUMBER | 0x03,
/**
* A tag whose value is a bool indicating whether a screen lock password is set for the device.
* A tag whose value is a bool indicating whether a screen lock password is required for the device.
*
* @syscap SystemCapability.Security.Asset
* @since 11
@ -423,12 +548,12 @@ declare namespace asset {
*/
SYNC_TYPE = TagType.NUMBER | 0x10,
/**
* A tag whose value is a 32-bit unsigned integer indicating when to delete Asset.
* A tag whose value is a bool indicating whether Asset is stored persistently.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
DELETE_TYPE = TagType.NUMBER | 0x11,
IS_PERSISTENT = TagType.BOOL | 0x11,
/**
* A tag whose value is a byte array indicating the first user-defined Asset data label (not allow to update).
*
@ -579,48 +704,48 @@ declare namespace asset {
* @since 11
*/
ACCESS_DENIED = 24000004,
/**
* The error code indicates that the authentication token has expired.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
AUTH_TOKEN_EXPIRED = 24000005,
/**
* The error code indicates that the screen lock status mismatches.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
STATUS_MISMATCH = 24000006,
STATUS_MISMATCH = 24000005,
/**
* The error code indicates insufficient memory.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
OUT_OF_MEMRORY = 24000007,
OUT_OF_MEMRORY = 24000006,
/**
* The error code indicates that the Asset or encryption key is corrupted.
* The error code indicates that the Asset is corrupted.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
DATA_CORRUPTED = 24000008,
/**
* The error code indicates that the ipc communication is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
IPC_ERROR = 24000009,
DATA_CORRUPTED = 24000007,
/**
* The error code indicates that the database operation is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
DATABASE_ERROR = 24000010,
DATABASE_ERROR = 24000008,
/**
* The error code indicates that the cryptography operation is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
CRYPTO_ERROR = 24000009,
/**
* The error code indicates that the ipc communication is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
IPC_ERROR = 24000010,
/**
* The error code indicates that the operation of calling bundle manager service is failed.
*
@ -628,55 +753,41 @@ declare namespace asset {
* @since 11
*/
BMS_ERROR = 24000011,
/**
* The error code indicates that the cryptography operation is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
CRYPTO_ERROR = 24000012,
/**
* The error code indicates that the operation of calling OS account service is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
ACCOUNT_ERROR = 24000013,
/**
* The error code indicates that the operation of calling common event service is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
COMMON_EVENT_ERROR = 24000014,
ACCOUNT_ERROR = 24000012,
/**
* The error code indicates that the operation of calling access token service is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
ACCESS_TOKEN_ERROR = 24000015,
ACCESS_TOKEN_ERROR = 24000013,
/**
* The error code indicates that the operation of file is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
FILE_OPERATION_ERROR = 24000016,
FILE_OPERATION_ERROR = 24000014,
/**
* The error code indicates that the operation of getting system time is failed.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
GET_SYSTEM_TIME_ERROR = 24000017,
GET_SYSTEM_TIME_ERROR = 24000015,
/**
* The error code indicates that the amount of map element or other limited quotas exceed the limit.
*
* @syscap SystemCapability.Security.Asset
* @since 11
*/
LIMIT_EXCEEDED = 24000018,
LIMIT_EXCEEDED = 24000016,
}
}

View File

@ -34,16 +34,14 @@ const std::unordered_map<int32_t, const char *> ERR_MSGS = {
{ ASSET_NOT_FOUND, "The queried Asset can not be found." },
{ ASSET_DUPLICATED, "The added Asset already exists." },
{ ASSET_ACCESS_DENIED, "The access to Asset is denied." },
{ ASSET_AUTH_TOKEN_EXPIRED, "The authentication token has expired." },
{ ASSET_STATUS_MISMATCH, "The screen lock status mismatches." },
{ ASSET_OUT_OF_MEMRORY, "Insufficient memory." },
{ ASSET_DATA_CORRUPTED, "The Asset or encryption key is corrupted." },
{ ASSET_DATA_CORRUPTED, "The Asset is corrupted." },
{ ASSET_IPC_ERROR, "Ipc communication is failed" },
{ ASSET_DATABASE_ERROR, "The database operation is failed." },
{ ASSET_BMS_ERROR, "The operation of calling bundle manager service is failed." },
{ ASSET_CRYPTO_ERROR, "The cryptography operation is failed." },
{ ASSET_ACCOUNT_ERROR, "The operation of calling OS account service is failed." },
{ ASSET_COMMON_EVENT_ERROR, "The operation of calling common event service is failed." },
{ ASSET_ACCESS_TOKEN_ERROR, "The operation of calling access token service is failed." },
{ ASSET_FILE_OPERATION_ERROR, "The operation of file is failed." },
{ ASSET_GET_SYSTEM_TIME_ERROR, "The operation of getting system time is failed." },

View File

@ -44,7 +44,7 @@ napi_value DeclareTag(napi_env env)
AddUint32Property(env, tag, "AUTH_CHALLENGE", ASSET_TAG_AUTH_CHALLENGE);
AddUint32Property(env, tag, "AUTH_TOKEN", ASSET_TAG_AUTH_TOKEN);
AddUint32Property(env, tag, "SYNC_TYPE", ASSET_TAG_SYNC_TYPE);
AddUint32Property(env, tag, "DELETE_TYPE", ASSET_TAG_DELETE_TYPE);
AddUint32Property(env, tag, "IS_PERSISTENT", ASSET_TAG_IS_PERSISTENT);
AddUint32Property(env, tag, "CONFLICT_RESOLUTION", ASSET_TAG_CONFLICT_RESOLUTION);
AddUint32Property(env, tag, "DATA_LABEL_CRITICAL_1", ASSET_TAG_DATA_LABEL_CRITICAL_1);
AddUint32Property(env, tag, "DATA_LABEL_CRITICAL_2", ASSET_TAG_DATA_LABEL_CRITICAL_2);
@ -72,16 +72,14 @@ napi_value DeclareErrorCode(napi_env env)
AddUint32Property(env, errorCode, "NOT_FOUND", ASSET_NOT_FOUND);
AddUint32Property(env, errorCode, "DUPLICATED", ASSET_DUPLICATED);
AddUint32Property(env, errorCode, "ACCESS_DENIED", ASSET_ACCESS_DENIED);
AddUint32Property(env, errorCode, "AUTH_TOKEN_EXPIRED", ASSET_AUTH_TOKEN_EXPIRED);
AddUint32Property(env, errorCode, "STATUS_MISMATCH", ASSET_STATUS_MISMATCH);
AddUint32Property(env, errorCode, "OUT_OF_MEMRORY", ASSET_OUT_OF_MEMRORY);
AddUint32Property(env, errorCode, "DATA_CORRUPTED", ASSET_DATA_CORRUPTED);
AddUint32Property(env, errorCode, "IPC_ERROR", ASSET_IPC_ERROR);
AddUint32Property(env, errorCode, "DATABASE_ERROR", ASSET_DATABASE_ERROR);
AddUint32Property(env, errorCode, "BMS_ERROR", ASSET_BMS_ERROR);
AddUint32Property(env, errorCode, "CRYPTO_ERROR", ASSET_CRYPTO_ERROR);
AddUint32Property(env, errorCode, "IPC_ERROR", ASSET_IPC_ERROR);
AddUint32Property(env, errorCode, "BMS_ERROR", ASSET_BMS_ERROR);
AddUint32Property(env, errorCode, "ACCOUNT_ERROR", ASSET_ACCOUNT_ERROR);
AddUint32Property(env, errorCode, "COMMON_EVENT_ERROR", ASSET_COMMON_EVENT_ERROR);
AddUint32Property(env, errorCode, "ACCESS_TOKEN_ERROR", ASSET_ACCESS_TOKEN_ERROR);
AddUint32Property(env, errorCode, "FILE_OPERATION_ERROR", ASSET_FILE_OPERATION_ERROR);
AddUint32Property(env, errorCode, "GET_SYSTEM_TIME_ERROR", ASSET_GET_SYSTEM_TIME_ERROR);
@ -118,15 +116,6 @@ napi_value DeclareSyncType(napi_env env)
return syncType;
}
napi_value DeclareDeleteType(napi_env env)
{
napi_value deleteType = nullptr;
NAPI_CALL(env, napi_create_object(env, &deleteType));
AddUint32Property(env, deleteType, "WHEN_USER_REMOVED", ASSET_DELETE_WHEN_USER_REMOVED);
AddUint32Property(env, deleteType, "WHEN_PACKAGE_REMOVED", ASSET_DELETE_WHEN_PACKAGE_REMOVED);
return deleteType;
}
napi_value DeclareConflictResolution(napi_env env)
{
napi_value conflictResolution = nullptr;
@ -223,7 +212,6 @@ napi_value Register(napi_env env, napi_value exports)
DECLARE_NAPI_PROPERTY("Accessibility", DeclareAccessibility(env)),
DECLARE_NAPI_PROPERTY("AuthType", DeclareAuthType(env)),
DECLARE_NAPI_PROPERTY("SyncType", DeclareSyncType(env)),
DECLARE_NAPI_PROPERTY("DeleteType", DeclareDeleteType(env)),
DECLARE_NAPI_PROPERTY("ConflictResolution", DeclareConflictResolution(env)),
DECLARE_NAPI_PROPERTY("ReturnType", DeclareReturnType(env)),
};

View File

@ -29,6 +29,16 @@ pub fn log_func_i(log: &str) {
hilog_rust::info!(log_label, "{}", @public(log));
}
/// the function to print log, and may be should not be used instead of logw
pub fn log_func_w(log: &str) {
let log_label = hilog_rust::HiLogLabel {
log_type: hilog_rust::LogType::LogCore,
domain: 0xD002F70, // Security Domain ID: 0xD002F00 - 0xD002FFF
tag: "Asset",
};
hilog_rust::warn!(log_label, "{}", @public(log));
}
/// the function to print log, and may be should not be used instead of loge
pub fn log_func_e(log: &str) {
let log_label = hilog_rust::HiLogLabel {
@ -53,6 +63,20 @@ macro_rules! logi {
);
}
/// Print logs at the info level.
///
/// # Examples
///
/// ```
/// logw!("hello, {}", "world");
/// ```
#[macro_export]
macro_rules! logw {
($($arg:tt)*) => (
$crate::log_func_w(&format!($($arg)*));
);
}
/// Print logs at the error level.
///
/// # Examples

View File

@ -1,57 +1,30 @@
# Copyright (c) 2022 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
# Copyright (c) 2023 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
# 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.
#####################################################
# below is the format of defining event #
#####################################################
#domain: domain name. [Only one domain name can be defined at the top]
#
#author: the author name who defined this event.
#date: the date when this event was defined, format is YYYY-MM-DD.
#logged: source file which refer to this event.
#usage: the usage of this event.
#//Define event name and event properties.
#@EVENT_NAME: the event definition part begin.
# // __BASE is used for defining the basic info of the event.
# // "type" optional values are: FAULT, STATISTICS, SECURITY, BEHAVIOR.
# // "level" optional values are: CRITICAL, MINOR.
# // "tag" set tags with may be used by subscriber of this event, multiple tags divided by space.
# // "desc" full description of this event.
# @PARAMETER: {type: parameter type, arrsize: array length(optional), desc: parameter description}.
# // follow the __BASE block, each line defines a parameter of this event.
# // "type" optional values are: INT8, UINT8, INT16, UINT16, INT32, UINT32, INT64, UINT64, FLOAT, DOUBLE, STRING.
# // "arrsize" of the parameter is an array, set a non-zero value.
# // "desc" full description of this parameter.
#####################################################
# Example of some hiviewdfx events definition #
#####################################################
# 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.
domain: ASSET
SECRET_STORE_OPERATION_FAILED:
__BASE: {type: FAULT, level: CRITICAL, desc: The event is asset fault }
FUNCTION: {type: STRING, desc: function name }
USER_ID: {type: INT32, desc: user id }
CALLER: {type: STRING, desc: caller info }
ERROR_CODE: {type: INT32, desc: error code }
EXTRA: {type: STRING, desc: extra data }
SECRET_STORE_INFO_COLLECTION:
__BASE: {type: STATISTIC, level: MINOR, desc: The event is api visit statistic }
FUNCTION: {type: STRING, desc: function name }
USER_ID: {type: INT32, desc: user id }
CALLER: {type: STRING, desc: caller info }
RUN_TIME: {type: UINT32, desc: running time }
EXTRA: {type: STRING, desc: extra data }
__BASE: {type: STATISTIC, level: MINOR, desc: statistic event for asset}
FUNCTION: {type: STRING, desc: function name}
USER_ID: {type: INT32, desc: user id}
CALLER: {type: STRING, desc: caller info}
RUN_TIME: {type: UINT32, desc: running time}
EXTRA: {type: STRING, desc: extra data}
SECRET_STORE_OPERATION_FAILED:
__BASE: {type: FAULT, level: CRITICAL, desc: fault event for asset}
FUNCTION: {type: STRING, desc: function name}
USER_ID: {type: INT32, desc: user id}
CALLER: {type: STRING, desc: caller info}
ERROR_CODE: {type: INT32, desc: error code}
EXTRA: {type: STRING, desc: extra data}

View File

@ -111,9 +111,9 @@ typedef enum {
*/
ASSET_TAG_SYNC_TYPE = ASSET_TYPE_NUMBER | 0x10,
/**
* A tag whose value is a 32-bit unsigned integer indicating when to delete Asset.
* A tag whose value is a bool indicating whether Asset is stored persistently.
*/
ASSET_TAG_DELETE_TYPE = ASSET_TYPE_NUMBER | 0x11,
ASSET_TAG_IS_PERSISTENT = ASSET_TYPE_BOOL | 0x11,
/**
* A tag whose value is a byte array indicating the first user-defined Asset data label (not allow to update).
*/
@ -206,62 +206,54 @@ typedef enum {
* The error code indicates that the access to Asset is denied.
*/
ASSET_ACCESS_DENIED = 24000004,
/**
* The error code indicates that the authentication token has expired.
*/
ASSET_AUTH_TOKEN_EXPIRED = 24000005,
/**
* The error code indicates that the screen lock status mismatches.
*/
ASSET_STATUS_MISMATCH = 24000006,
ASSET_STATUS_MISMATCH = 24000005,
/**
* The error code indicates insufficient memory.
*/
ASSET_OUT_OF_MEMRORY = 24000007,
ASSET_OUT_OF_MEMRORY = 24000006,
/**
* The error code indicates that the Asset or encryption key is corrupted.
* The error code indicates that the Asset is corrupted.
*/
ASSET_DATA_CORRUPTED = 24000008,
/**
* The error code indicates that the ipc communication is failed.
*/
ASSET_IPC_ERROR = 24000009,
ASSET_DATA_CORRUPTED = 24000007,
/**
* The error code indicates that the database operation is failed.
*/
ASSET_DATABASE_ERROR = 24000010,
ASSET_DATABASE_ERROR = 24000008,
/**
* The error code indicates that the cryptography operation is failed.
*/
ASSET_CRYPTO_ERROR = 2400009,
/**
* The error code indicates that the ipc communication is failed.
*/
ASSET_IPC_ERROR = 24000010,
/**
* The error code indicates that the operation of calling bundle manager service is failed.
*/
ASSET_BMS_ERROR = 24000011,
/**
* The error code indicates that the cryptography operation is failed.
*/
ASSET_CRYPTO_ERROR = 24000012,
/**
* The error code indicates that the operation of calling OS account service is failed.
*/
ASSET_ACCOUNT_ERROR = 24000013,
/**
* The error code indicates that the operation of calling common event service is failed.
*/
ASSET_COMMON_EVENT_ERROR = 24000014,
ASSET_ACCOUNT_ERROR = 24000012,
/**
* The error code indicates that the operation of calling access token service is failed.
*/
ASSET_ACCESS_TOKEN_ERROR = 24000015,
ASSET_ACCESS_TOKEN_ERROR = 24000013,
/**
* The error code indicates that the operation of file is failed.
*/
ASSET_FILE_OPERATION_ERROR = 24000016,
ASSET_FILE_OPERATION_ERROR = 24000014,
/**
* The error code indicates that the operation of getting system time is failed.
*/
ASSET_GET_SYSTEM_TIME_ERROR = 24000017,
ASSET_GET_SYSTEM_TIME_ERROR = 24000015,
/**
* The error code indicates that the amount of map element or other limited quotas exceed the limit.
*/
ASSET_LIMIT_EXCEEDED = 24000018,
ASSET_LIMIT_EXCEEDED = 24000016,
} Asset_ResultCode;
/**
@ -320,22 +312,6 @@ typedef enum {
ASSET_SYNC_TYPE_TRUSTED_DEVICE = 1 << 1,
} Asset_SyncType;
/**
* @brief enum type indicates the type of when to delete Asset.
*
* @since 11
*/
typedef enum {
/**
* The Asset is deleted when the user space it belongs to is removed.
*/
ASSET_DELETE_WHEN_USER_REMOVED = 1 << 0,
/**
* The Asset is deleted when the package it belongs to is removed.
*/
ASSET_DELETE_WHEN_PACKAGE_REMOVED = 1 << 1,
} Asset_DeleteType;
/**
* @brief An enum type indicates the strategy for conflict resolution when handling duplicated Asset alias.
*

View File

@ -28,9 +28,25 @@ pub struct CallingInfo {
owner_info: Vec<u8>,
}
#[allow(dead_code)]
#[repr(C)]
enum ResultCode {
Success = 0,
InvalidArgument = 1,
BmsError = 2,
AccessTokenError = 3,
Unsupported = 4,
}
extern "C" {
fn GetUserIdByUid(uid: u64, userId: &mut i32) -> bool;
fn GetOwnerInfo(userId: i32, uid: u64, ownerType: *mut OwnerType, ownerInfo: *mut u8, infoLen: *mut u32) -> bool;
fn GetOwnerInfo(
userId: i32,
uid: u64,
ownerType: *mut OwnerType,
ownerInfo: *mut u8,
infoLen: *mut u32,
) -> ResultCode;
}
pub(crate) fn get_user_id(uid: u64) -> Result<i32> {
@ -62,13 +78,19 @@ impl CallingInfo {
let mut owner_info = vec![0u8; 256];
let mut len = 256u32;
let mut owner_type = OwnerType::Hap;
unsafe {
if !GetOwnerInfo(user_id, uid, &mut owner_type, owner_info.as_mut_ptr(), &mut len) {
return log_throw_error!(ErrCode::BmsError, "[FATAL]Get owner info from bms failed.");
}
let err = unsafe { GetOwnerInfo(user_id, uid, &mut owner_type, owner_info.as_mut_ptr(), &mut len) };
match err {
ResultCode::Success => {
owner_info.truncate(len as usize);
Ok(CallingInfo { user_id, owner_type, owner_info })
},
ResultCode::InvalidArgument => log_throw_error!(ErrCode::InvalidArgument, "[FATAL]Invalid argument."),
ResultCode::BmsError => log_throw_error!(ErrCode::BmsError, "[FATAL]Get owner info from bms failed."),
ResultCode::AccessTokenError => {
log_throw_error!(ErrCode::AccessTokenError, "[FATAL]Get process info failed.")
},
ResultCode::Unsupported => log_throw_error!(ErrCode::NotSupport, "[FATAL]Unsupported calling type."),
}
owner_info.truncate(len as usize);
Ok(CallingInfo { user_id, owner_type, owner_info })
}
/// Get owner type of calling.

View File

@ -30,7 +30,7 @@ const TAG_COLUMN_TABLE: [(Tag, &str); 15] = [
(Tag::Accessibility, column::ACCESSIBILITY),
(Tag::AuthType, column::AUTH_TYPE),
(Tag::SyncType, column::SYNC_TYPE),
(Tag::DeleteType, column::DELETE_TYPE),
(Tag::IsPersistent, column::IS_PERSISTENT),
(Tag::RequirePasswordSet, column::REQUIRE_PASSWORD_SET),
(Tag::DataLabelCritical1, column::CRITICAL1),
(Tag::DataLabelCritical2, column::CRITICAL2),
@ -51,7 +51,7 @@ const AAD_ATTR: [&str; 14] = [
column::ACCESSIBILITY,
column::REQUIRE_PASSWORD_SET,
column::AUTH_TYPE,
column::DELETE_TYPE,
column::IS_PERSISTENT,
column::VERSION,
column::CRITICAL1,
column::CRITICAL2,
@ -66,7 +66,7 @@ pub(crate) const NORMAL_LABEL_ATTRS: [Tag; 4] =
[Tag::DataLabelNormal1, Tag::DataLabelNormal2, Tag::DataLabelNormal3, Tag::DataLabelNormal4];
pub(crate) const ACCESS_CONTROL_ATTRS: [Tag; 6] =
[Tag::Alias, Tag::Accessibility, Tag::AuthType, Tag::DeleteType, Tag::SyncType, Tag::RequirePasswordSet];
[Tag::Alias, Tag::Accessibility, Tag::AuthType, Tag::IsPersistent, Tag::SyncType, Tag::RequirePasswordSet];
pub(crate) fn get_cloumn_name(tag: Tag) -> Option<&'static str> {
for (table_tag, table_column) in TAG_COLUMN_TABLE {

View File

@ -36,8 +36,6 @@ const AUTH_TOKEN_SIZE: usize = 148;
const CHALLENGE_SIZE: usize = 32;
const SYNC_TYPE_MIN_BITS: u32 = 0;
const SYNC_TYPE_MAX_BITS: u32 = 2;
const DELETE_TYPE_MIN_BITS: u32 = 1;
const DELETE_TYPE_MAX_BITS: u32 = 2;
fn check_data_type(tag: &Tag, value: &Value) -> Result<()> {
if tag.data_type() != value.data_type() {
@ -134,13 +132,12 @@ fn check_data_value(tag: &Tag, value: &Value) -> Result<()> {
Tag::Secret => check_array_size(tag, value, MIN_ARRAY_SIZE, MAX_ARRAY_SIZE),
Tag::Alias => check_array_size(tag, value, MIN_ARRAY_SIZE, MAX_ALIAS_SIZE),
Tag::Accessibility => check_enum_variant::<Accessibility>(tag, value),
Tag::RequirePasswordSet => Ok(()),
Tag::RequirePasswordSet | Tag::IsPersistent => Ok(()),
Tag::AuthType => check_enum_variant::<AuthType>(tag, value),
Tag::AuthValidityPeriod => check_number_range(tag, value, MIN_NUMBER_VALUE, MAX_AUTH_VALID_PERIOD),
Tag::AuthChallenge => check_array_size(tag, value, CHALLENGE_SIZE - 1, CHALLENGE_SIZE),
Tag::AuthToken => check_array_size(tag, value, AUTH_TOKEN_SIZE - 1, AUTH_TOKEN_SIZE),
Tag::SyncType => check_valid_bits(tag, value, SYNC_TYPE_MIN_BITS, SYNC_TYPE_MAX_BITS),
Tag::DeleteType => check_valid_bits(tag, value, DELETE_TYPE_MIN_BITS, DELETE_TYPE_MAX_BITS),
Tag::ConflictResolution => check_enum_variant::<ConflictResolution>(tag, value),
Tag::DataLabelCritical1 | Tag::DataLabelCritical2 | Tag::DataLabelCritical3 | Tag::DataLabelCritical4 => {
check_array_size(tag, value, MIN_ARRAY_SIZE, MAX_LABEL_SIZE)

View File

@ -22,8 +22,8 @@ use asset_db_operator::{
types::{column, DbMap, DB_DATA_VERSION},
};
use asset_definition::{
log_throw_error, Accessibility, AssetMap, AuthType, ConflictResolution, DeleteType, ErrCode, Extension, Result,
SyncType, Tag, Value,
log_throw_error, Accessibility, AssetMap, AuthType, ConflictResolution, ErrCode, Extension, Result, SyncType, Tag,
Value,
};
use asset_log::logi;
use asset_utils::time;
@ -93,13 +93,12 @@ fn add_default_attrs(db_data: &mut DbMap) {
db_data.entry(column::ACCESSIBILITY).or_insert(Value::Number(Accessibility::default() as u32));
db_data.entry(column::AUTH_TYPE).or_insert(Value::Number(AuthType::default() as u32));
db_data.entry(column::SYNC_TYPE).or_insert(Value::Number(SyncType::default() as u32));
db_data.entry(column::REQUIRE_PASSWORD_SET).or_insert(Value::Bool(false));
let delete_type = DeleteType::WhenUserRemoved as u32 | DeleteType::WhenPackageRemoved as u32;
db_data.entry(column::DELETE_TYPE).or_insert(Value::Number(delete_type));
db_data.entry(column::REQUIRE_PASSWORD_SET).or_insert(Value::Bool(bool::default()));
db_data.entry(column::IS_PERSISTENT).or_insert(Value::Bool(bool::default()));
}
const REQUIRED_ATTRS: [Tag; 2] = [Tag::Secret, Tag::Alias];
const OPTIONAL_ATTRS: [Tag; 3] = [Tag::Secret, Tag::ConflictResolution, Tag::DeleteType];
const OPTIONAL_ATTRS: [Tag; 3] = [Tag::Secret, Tag::ConflictResolution, Tag::IsPersistent];
const SYSTEM_USER_ID_MAX: i32 = 99;
fn check_accessibity_validity(attributes: &AssetMap, calling_info: &CallingInfo) -> Result<()> {

View File

@ -36,6 +36,7 @@ extern "C" {
}
const HKS_SUCCESS: i32 = 0;
const HKS_ERROR_KEY_AUTH_VERIFY_FAILED: i32 = -47;
const NONCE_SIZE: usize = 12;
const TAG_SIZE: usize = 16;
const HANDLE_LEN: usize = 8;
@ -109,6 +110,9 @@ impl Crypto {
};
match ret {
HKS_SUCCESS => Ok(msg),
HKS_ERROR_KEY_AUTH_VERIFY_FAILED => {
log_throw_error!(ErrCode::AccessDenied, "[FATAL]HUKS verify auth token failed")
},
_ => log_throw_error!(ErrCode::CryptoError, "[FATAL]HUKS execute crypt failed, ret: {}", ret),
}
}

View File

@ -108,14 +108,15 @@ int32_t GenerateKey(const struct KeyId *keyId, bool needAuth, bool requirePasswo
}
}
if (requirePasswordSet) {
struct HksParam tempParam = { .tag = HKS_TAG_IS_DEVICE_PASSWORD_SET, .boolParam = true };
ret = HksAddParams(paramSet, &tempParam, 1); // 1: add one param to paramSet
if (ret != HKS_SUCCESS) {
LOGE("[FATAL]HUKS add requirePasswordSet param failed. error=%{public}d", ret);
break;
}
}
(void)requirePasswordSet;
// if (requirePasswordSet) {
// struct HksParam tempParam = { .tag = HKS_TAG_IS_DEVICE_PASSWORD_SET, .boolParam = true };
// ret = HksAddParams(paramSet, &tempParam, 1); // 1: add one param to paramSet
// if (ret != HKS_SUCCESS) {
// LOGE("[FATAL]HUKS add requirePasswordSet param failed. error=%{public}d", ret);
// break;
// }
// }
ret = HksBuildParamSet(&paramSet);
if (ret != HKS_SUCCESS) {

View File

@ -144,7 +144,7 @@ impl SecretKey {
let _identity = IdentityScope::build()?;
let ret = unsafe { DeleteKey(&key_alias as *const HksBlob) };
match ret {
HKS_SUCCESS => Ok(()),
HKS_SUCCESS | HKS_ERROR_NOT_EXIST => Ok(()),
_ => {
log_throw_error!(ErrCode::CryptoError, "[FATAL]secret key delete failed ret {}", ret)
},

View File

@ -21,7 +21,7 @@ use std::{ffi::CStr, fs, ptr::null_mut, sync::Mutex};
use asset_constants::OwnerType;
use asset_definition::{log_throw_error, ErrCode, Extension, Result};
use asset_log::{loge, logi};
use asset_log::loge;
use crate::{
statement::Statement,
@ -120,10 +120,13 @@ impl Database {
/// Open the database connection and recovery the database if the connection fails.
fn open_and_recovery(&mut self) -> Result<()> {
match self.open() {
let result = self.open();
#[cfg(test)]
let result = match result {
Err(ret) if ret.code == ErrCode::DataCorrupted => self.recovery(),
ret => ret,
}
};
result
}
/// Close database connection.
@ -135,8 +138,9 @@ impl Database {
}
// Recovery the corrupt database and reopen it.
#[cfg(test)]
pub(crate) fn recovery(&mut self) -> Result<()> {
logi!("[WARNING]Database is corrupt, start to recovery, path={}", self.path);
loge!("[WARNING]Database is corrupt, start to recovery, path={}", self.path);
self.close();
if let Err(e) = fs::copy(&self.backup_path, &self.path) {
return log_throw_error!(ErrCode::FileOperationError, "[FATAL][DB]Recovery database failed, err={}", e);
@ -168,12 +172,13 @@ impl Database {
/// Delete database file.
pub fn delete(user_id: i32) -> Result<()> {
let path = fmt_db_path(user_id);
let backup_path = fmt_backup_path(&path);
let _backup_path = fmt_backup_path(&path);
if let Err(e) = fs::remove_file(path) {
return log_throw_error!(ErrCode::FileOperationError, "[FATAL][DB]Delete database failed, err={}", e);
}
if let Err(e) = fs::remove_file(backup_path) {
#[cfg(test)]
if let Err(e) = fs::remove_file(_backup_path) {
return log_throw_error!(
ErrCode::FileOperationError,
"[FATAL][DB]Delete backup database failed, err={}",
@ -221,9 +226,11 @@ impl Database {
/// do same operation in backup database when do something in main db
/// backup every success operation, recovery every fail operation
pub(crate) fn execute_and_backup<T, F: Fn(&Table) -> Result<T>>(&mut self, modified: bool, func: F) -> Result<T> {
pub(crate) fn execute_and_backup<T, F: Fn(&Table) -> Result<T>>(&mut self, _modified: bool, func: F) -> Result<T> {
let table = Table::new(TABLE_NAME, self);
let ret = match func(&table) {
let result = func(&table);
#[cfg(test)]
let result = match result {
Err(ret) if ret.code == ErrCode::DataCorrupted => {
self.recovery()?;
let table = Table::new(TABLE_NAME, self); // Database handle will be changed.
@ -232,10 +239,11 @@ impl Database {
ret => ret,
};
if ret.is_ok() && modified && fs::copy(&self.path, &self.backup_path).is_err() {
#[cfg(test)]
if result.is_ok() && _modified && fs::copy(&self.path, &self.backup_path).is_err() {
loge!("[WARNING]Backup database {} failed", self.backup_path);
}
ret
result
}
/// Insert datas into database.

View File

@ -33,7 +33,7 @@ const DB_DATA: [(&str, Value); 9] = [
(column::SYNC_TYPE, Value::Number(1)),
(column::ACCESSIBILITY, Value::Number(1)),
(column::AUTH_TYPE, Value::Number(1)),
(column::DELETE_TYPE, Value::Number(1)),
(column::IS_PERSISTENT, Value::Bool(true)),
(column::VERSION, Value::Number(1)),
(column::CREATE_TIME, Value::Number(1)),
(column::UPDATE_TIME, Value::Number(1)),

View File

@ -50,8 +50,8 @@ pub mod column {
pub const CREATE_TIME: &str = "CreateTime";
/// Column name of the data update time.
pub const UPDATE_TIME: &str = "UpdateTime";
/// Column name of the data deletion type.
pub const DELETE_TYPE: &str = "DeleteType";
/// Column name of the data persistence attribute.
pub const IS_PERSISTENT: &str = "IsPersistent";
/// Column name of the data version number.
pub const VERSION: &str = "Version";
/// Column name of if data require password set
@ -94,7 +94,7 @@ pub(crate) const COLUMN_INFO: &[ColumnInfo] = &[
ColumnInfo { name: column::AUTH_TYPE, data_type: DataType::Number, is_primary_key: false, not_null: true },
ColumnInfo { name: column::CREATE_TIME, data_type: DataType::Bytes, is_primary_key: false, not_null: true },
ColumnInfo { name: column::UPDATE_TIME, data_type: DataType::Bytes, is_primary_key: false, not_null: true },
ColumnInfo { name: column::DELETE_TYPE, data_type: DataType::Number, is_primary_key: false, not_null: true },
ColumnInfo { name: column::IS_PERSISTENT, data_type: DataType::Bool, is_primary_key: false, not_null: true },
ColumnInfo { name: column::VERSION, data_type: DataType::Number, is_primary_key: false, not_null: true },
ColumnInfo { name: column::REQUIRE_PASSWORD_SET, data_type: DataType::Bool, is_primary_key: false, not_null: true },
ColumnInfo { name: column::CRITICAL1, data_type: DataType::Bytes, is_primary_key: false, not_null: false },

View File

@ -27,7 +27,15 @@ enum OwnerType {
NATIVE = 1,
};
bool GetOwnerInfo(int32_t userId, uint64_t uid, OwnerType *ownerType, uint8_t *ownerInfo, uint32_t *infoLen);
enum ResultCode {
SUCCESS = 0,
INVALID_ARGUMENT = 1,
BMS_ERROR = 2,
ACCESS_TOKEN_ERROR = 3,
UNSUPPORTED = 4,
};
ResultCode GetOwnerInfo(int32_t userId, uint64_t uid, OwnerType *ownerType, uint8_t *ownerInfo, uint32_t *infoLen);
#ifdef __cplusplus
}

View File

@ -30,67 +30,73 @@ using namespace AppExecFwk;
using namespace Security::AccessToken;
namespace {
bool GetHapInfo(int32_t userId, uint32_t tokenId, std::string &info)
ResultCode GetHapInfo(int32_t userId, uint32_t tokenId, std::string &info)
{
HapTokenInfo tokenInfo;
int32_t ret = AccessTokenKit::GetHapTokenInfo(tokenId, tokenInfo);
if (ret != RET_SUCCESS) {
LOGE("[FATAL]Get hap token info failed, ret = %{public}d", ret);
return false;
return ACCESS_TOKEN_ERROR;
}
AppExecFwk::BundleMgrClient bmsClient;
AppExecFwk::BundleInfo bundleInfo;
if (!bmsClient.GetBundleInfo(tokenInfo.bundleName, BundleFlag::GET_BUNDLE_WITH_HASH_VALUE, bundleInfo, userId)) {
LOGE("[FATAL]Get bundle info failed!");
return false;
return BMS_ERROR;
}
info = bundleInfo.appId + "_" + std::to_string(bundleInfo.appIndex);
return true;
return SUCCESS;
}
bool GetProcessInfo(uint32_t tokenId, uint64_t uid, std::string &info)
ResultCode GetProcessInfo(uint32_t tokenId, uint64_t uid, std::string &info)
{
NativeTokenInfo tokenInfo;
int32_t ret = AccessTokenKit::GetNativeTokenInfo(tokenId, tokenInfo);
if (ret != RET_SUCCESS) {
LOGE("[FATAL]Get native token info failed, ret = %{public}d", ret);
return false;
return ACCESS_TOKEN_ERROR;
}
info = tokenInfo.processName + "_" + std::to_string(uid);
return true;
return SUCCESS;
}
} // namespace
bool GetOwnerInfo(int32_t userId, uint64_t uid, OwnerType *ownerType, uint8_t *ownerInfo, uint32_t *infoLen)
ResultCode GetOwnerInfo(int32_t userId, uint64_t uid, OwnerType *ownerType, uint8_t *ownerInfo, uint32_t *infoLen)
{
if (ownerType == NULL || ownerInfo == NULL || infoLen == NULL) {
return false;
return INVALID_ARGUMENT;
}
auto tokenId = IPCSkeleton::GetCallingTokenID();
ATokenTypeEnum tokenType = AccessTokenKit::GetTokenTypeFlag(tokenId);
std::string info;
bool ret = false;
ResultCode code = SUCCESS;
switch (tokenType) {
case ATokenTypeEnum::TOKEN_HAP:
*ownerType = HAP;
ret = GetHapInfo(userId, tokenId, info);
code = GetHapInfo(userId, tokenId, info);
break;
case ATokenTypeEnum::TOKEN_NATIVE:
case ATokenTypeEnum::TOKEN_SHELL:
*ownerType = NATIVE;
ret = GetProcessInfo(tokenId, uid, info);
code = GetProcessInfo(tokenId, uid, info);
break;
default:
LOGE("[FATAL]Unsupported calling type: %{public}d", tokenType);
code = UNSUPPORTED;
}
if (ret && memcpy_s(ownerInfo, *infoLen, info.c_str(), info.size()) == EOK) {
LOGI("[INFO]Calling userId: %{public}d, info: %{public}s", userId, info.c_str());
*infoLen = info.size();
return true;
if (code != SUCCESS) {
return code;
}
return false;
if (memcpy_s(ownerInfo, *infoLen, info.c_str(), info.size()) != EOK) {
LOGE("The owner buffer is too small. Expect size: %{public}zu, actual size: %{public}u", info.size(), *infoLen);
return INVALID_ARGUMENT;
}
*infoLen = info.size();
return SUCCESS;
}

View File

@ -91,21 +91,18 @@ std::shared_ptr<SystemEventHandler> g_eventHandler = nullptr;
bool SubscribeSystemEvent(OnPackageRemoved onPackageRemoved, OnUserRemoved onUserRemoved, OnScreenOff onScreenOff)
{
if (g_eventHandler != nullptr) {
LOGI("The system event has been subscribed.");
return true;
}
MatchingSkills matchingSkills;
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_PACKAGE_REMOVED);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SANDBOX_PACKAGE_REMOVED);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_USER_REMOVED);
matchingSkills.AddEvent(CommonEventSupport::COMMON_EVENT_SCREEN_OFF);
CommonEventSubscribeInfo subscriberInfo(matchingSkills);
g_eventHandler = std::make_shared<SystemEventHandler>(subscriberInfo, onPackageRemoved, onUserRemoved, onScreenOff);
if (g_eventHandler == nullptr) {
LOGE("[FATAL]Asset system event handler is nullptr.");
return false;
g_eventHandler = std::make_shared<SystemEventHandler>(subscriberInfo, onPackageRemoved, onUserRemoved, onScreenOff);
if (g_eventHandler == nullptr) {
LOGE("[FATAL]Asset system event handler is nullptr.");
return false;
}
}
return CommonEventManager::SubscribeCommonEvent(g_eventHandler);

View File

@ -43,7 +43,7 @@ fn add_all_tags() {
attrs.insert_attr(Tag::Accessibility, Accessibility::DevicePowerOn);
attrs.insert_attr(Tag::AuthType, AuthType::Any);
attrs.insert_attr(Tag::SyncType, SyncType::ThisDevice);
attrs.insert_attr(Tag::DeleteType, DeleteType::WhenUserRemoved);
attrs.insert_attr(Tag::IsPersistent, true);
attrs.insert_attr(Tag::RequirePasswordSet, false);
attrs.insert_attr(Tag::ConflictResolution, ConflictResolution::Overwrite);
asset_sdk::Manager::build().unwrap().add(&attrs).unwrap();
@ -63,7 +63,7 @@ fn add_all_tags() {
assert_eq!(Accessibility::DevicePowerOn, res[0].get_enum_attr::<Accessibility>(&Tag::Accessibility).unwrap());
assert_eq!(AuthType::Any, res[0].get_enum_attr::<AuthType>(&Tag::AuthType).unwrap());
assert_eq!(SyncType::ThisDevice, res[0].get_enum_attr::<SyncType>(&Tag::SyncType).unwrap());
assert_eq!(DeleteType::WhenUserRemoved, res[0].get_enum_attr::<DeleteType>(&Tag::DeleteType).unwrap());
assert!(res[0].get_bool_attr(&Tag::IsPersistent).unwrap());
assert!(!res[0].get_bool_attr(&Tag::RequirePasswordSet).unwrap());
remove_by_alias(alias).unwrap();
@ -86,8 +86,7 @@ fn add_required_tags() {
assert_eq!(Accessibility::DevicePowerOn, res[0].get_enum_attr::<Accessibility>(&Tag::Accessibility).unwrap());
assert_eq!(AuthType::None, res[0].get_enum_attr::<AuthType>(&Tag::AuthType).unwrap());
assert_eq!(SyncType::Never, res[0].get_enum_attr::<SyncType>(&Tag::SyncType).unwrap());
let delete_type = (DeleteType::WhenUserRemoved as u32) | (DeleteType::WhenPackageRemoved as u32);
assert_eq!(delete_type, res[0].get_num_attr(&Tag::DeleteType).unwrap());
assert!(!res[0].get_bool_attr(&Tag::IsPersistent).unwrap());
assert!(!res[0].get_bool_attr(&Tag::RequirePasswordSet).unwrap());
remove_by_alias(func_name).unwrap();
}

View File

@ -162,20 +162,6 @@ fn add_invalid_accessibility() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().add(&attrs).unwrap_err());
}
#[test]
fn add_required_pwd_with_unmatched_type() {
let function_name = function!().as_bytes();
let mut attrs = AssetMap::new();
attrs.insert_attr(Tag::Alias, function_name.to_owned());
attrs.insert_attr(Tag::Secret, function_name.to_owned());
attrs.insert_attr(Tag::RequirePasswordSet, vec![]);
attrs.insert_attr(Tag::Accessibility, Accessibility::DevicePowerOn);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().add(&attrs).unwrap_err());
attrs.insert_attr(Tag::RequirePasswordSet, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().add(&attrs).unwrap_err());
}
#[test]
fn add_invalid_auth_type() {
let function_name = function!().as_bytes();
@ -216,18 +202,6 @@ fn add_sync_type_with_max_len() {
remove_by_alias(function_name).unwrap();
}
#[test]
fn add_invalid_delete_type() {
let function_name = function!().as_bytes();
let mut attrs = AssetMap::new();
attrs.insert_attr(Tag::Alias, function_name.to_owned());
attrs.insert_attr(Tag::Secret, function_name.to_owned());
attrs.insert_attr(Tag::Accessibility, Accessibility::DevicePowerOn);
let delete_type = DeleteType::WhenPackageRemoved as u32 | DeleteType::WhenUserRemoved as u32;
attrs.insert_attr(Tag::DeleteType, delete_type + 1);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().add(&attrs).unwrap_err());
}
#[test]
fn add_invalid_conflict_resolution() {
let function_name = function!().as_bytes();
@ -257,7 +231,24 @@ fn add_invalid_label() {
}
#[test]
fn add_label_with_unmatched_type() {
fn add_bool_tag_with_unmatched_type() {
let tags = [Tag::RequirePasswordSet, Tag::IsPersistent];
let function_name = function!().as_bytes();
for tag in tags {
let mut attrs = AssetMap::new();
attrs.insert_attr(Tag::Alias, function_name.to_owned());
attrs.insert_attr(Tag::Secret, function_name.to_owned());
attrs.insert_attr(Tag::Accessibility, Accessibility::DevicePowerOn);
attrs.insert_attr(tag, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().add(&attrs).unwrap_err());
attrs.insert_attr(tag, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().add(&attrs).unwrap_err());
}
}
#[test]
fn add_bytes_tag_with_unmatched_type() {
let function_name = function!().as_bytes();
let labels = &[CRITICAL_LABEL_ATTRS, NORMAL_LABEL_ATTRS].concat();
for &label in labels {
@ -275,7 +266,7 @@ fn add_label_with_unmatched_type() {
#[test]
fn add_number_tag_with_unmatched_type() {
let tags_num = [Tag::Accessibility, Tag::AuthType, Tag::SyncType, Tag::DeleteType, Tag::ConflictResolution];
let tags_num = [Tag::Accessibility, Tag::AuthType, Tag::SyncType, Tag::ConflictResolution];
for tag in tags_num {
let mut attrs = AssetMap::new();
attrs.insert_attr(tag, vec![]);

View File

@ -43,8 +43,6 @@ pub(crate) const AUTH_TOKEN_SIZE: usize = 148;
pub(crate) const CHALLENGE_SIZE: usize = 32;
pub(crate) const SYNC_TYPE_MIN_BITS: u32 = 0;
pub(crate) const SYNC_TYPE_MAX_BITS: u32 = 3;
pub(crate) const DELETE_TYPE_MIN_BITS: u32 = 1;
pub(crate) const DELETE_TYPE_MAX_BITS: u32 = 2;
pub(crate) const CRITICAL_LABEL_ATTRS: [Tag; 4] =
[Tag::DataLabelCritical1, Tag::DataLabelCritical2, Tag::DataLabelCritical3, Tag::DataLabelCritical4];

View File

@ -55,7 +55,6 @@ fn post_query_unsupported_tags() {
Tag::AuthType,
Tag::AuthValidityPeriod,
Tag::SyncType,
Tag::DeleteType,
Tag::ReturnType,
Tag::ReturnLimit,
Tag::ReturnOffset,
@ -68,7 +67,7 @@ fn post_query_unsupported_tags() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().post_query(&query).unwrap_err());
}
let tags_bool = [Tag::RequirePasswordSet];
let tags_bool = [Tag::RequirePasswordSet, Tag::IsPersistent];
for tag in tags_bool {
let mut query = AssetMap::new();
query.insert_attr(tag, true);

View File

@ -58,12 +58,12 @@ fn pre_query_with_unsupported_auth_type() {
}
#[test]
fn pre_query_with_wrong_delete_type() {
fn pre_query_with_wrong_persistent() {
let function_name = function!().as_bytes();
add_default_auth_asset(function_name, function_name).unwrap();
let mut query = AssetMap::new();
query.insert_attr(Tag::DeleteType, DeleteType::WhenUserRemoved);
query.insert_attr(Tag::IsPersistent, true);
expect_error_eq(ErrCode::NotFound, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
remove_by_alias(function_name).unwrap();
}

View File

@ -33,16 +33,6 @@ fn pre_query_invalid_accessibility() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
}
#[test]
fn pre_query_required_pwd_with_unmatched_type() {
let mut query = AssetMap::new();
query.insert_attr(Tag::RequirePasswordSet, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
query.insert_attr(Tag::RequirePasswordSet, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
}
#[test]
fn pre_query_invalid_auth_type() {
let mut query = AssetMap::new();
@ -61,14 +51,6 @@ fn pre_query_invalid_sync_type() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
}
#[test]
fn pre_query_invalid_delete_type() {
let mut query = AssetMap::new();
let delete_type = DeleteType::WhenPackageRemoved as u32 | DeleteType::WhenUserRemoved as u32;
query.insert_attr(Tag::DeleteType, delete_type + 1);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
}
#[test]
fn pre_query_invalid_auth_validity_period() {
let mut query = AssetMap::new();
@ -92,6 +74,19 @@ fn pre_query_invalid_label() {
}
}
#[test]
fn pre_query_bool_tag_with_unmatched_type() {
let tags = [Tag::RequirePasswordSet, Tag::IsPersistent];
for tag in tags {
let mut query = AssetMap::new();
query.insert_attr(tag, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
query.insert_attr(tag, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().pre_query(&query).unwrap_err());
}
}
#[test]
fn pre_query_bytes_tag_with_unmatched_type() {
let mut tags_bytes = [CRITICAL_LABEL_ATTRS, NORMAL_LABEL_ATTRS].concat();
@ -108,7 +103,7 @@ fn pre_query_bytes_tag_with_unmatched_type() {
#[test]
fn pre_query_number_tag_with_unmatched_type() {
let tags_num = [Tag::Accessibility, Tag::AuthType, Tag::SyncType, Tag::DeleteType, Tag::AuthValidityPeriod];
let tags_num = [Tag::Accessibility, Tag::AuthType, Tag::SyncType, Tag::AuthValidityPeriod];
for tag in tags_num {
let mut query = AssetMap::new();
query.insert_attr(tag, vec![]);

View File

@ -34,16 +34,6 @@ fn query_invalid_accessibility() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
}
#[test]
fn query_required_pwd_with_unmatched_type() {
let mut query = AssetMap::new();
query.insert_attr(Tag::RequirePasswordSet, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
query.insert_attr(Tag::RequirePasswordSet, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
}
#[test]
fn query_invalid_auth_type() {
let mut query = AssetMap::new();
@ -62,14 +52,6 @@ fn query_invalid_sync_type() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
}
#[test]
fn query_invalid_delete_type() {
let mut query = AssetMap::new();
let delete_type = DeleteType::WhenPackageRemoved as u32 | DeleteType::WhenUserRemoved as u32;
query.insert_attr(Tag::DeleteType, delete_type + 1);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
}
#[test]
fn query_invalid_label() {
let labels = &[CRITICAL_LABEL_ATTRS, NORMAL_LABEL_ATTRS].concat();
@ -102,7 +84,7 @@ fn query_invalid_return_ordered_by() {
Tag::RequirePasswordSet,
Tag::AuthType,
Tag::SyncType,
Tag::DeleteType,
Tag::IsPersistent,
Tag::AuthValidityPeriod,
Tag::ReturnType,
Tag::ReturnLimit,
@ -166,6 +148,19 @@ fn query_with_auth_challenge_without_auth_token() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
}
#[test]
fn query_bool_tag_with_unmatched_type() {
let tags = [Tag::RequirePasswordSet, Tag::IsPersistent];
for tag in tags {
let mut query = AssetMap::new();
query.insert_attr(tag, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
query.insert_attr(tag, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().query(&query).unwrap_err());
}
}
#[test]
fn query_bytes_tag_with_unmatched_type() {
let mut tags_bytes = [CRITICAL_LABEL_ATTRS, NORMAL_LABEL_ATTRS].concat();
@ -186,7 +181,6 @@ fn query_number_tag_with_unmatched_type() {
Tag::Accessibility,
Tag::AuthType,
Tag::SyncType,
Tag::DeleteType,
Tag::ReturnLimit,
Tag::ReturnOffset,
Tag::ReturnOrderedBy,

View File

@ -34,16 +34,6 @@ fn remove_invalid_accessibility() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
}
#[test]
fn remove_required_pwd_with_unmatched_type() {
let mut query = AssetMap::new();
query.insert_attr(Tag::RequirePasswordSet, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
query.insert_attr(Tag::RequirePasswordSet, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
}
#[test]
fn remove_invalid_auth_type() {
let mut query = AssetMap::new();
@ -62,14 +52,6 @@ fn remove_invalid_sync_type() {
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
}
#[test]
fn remove_invalid_delete_type() {
let mut query = AssetMap::new();
let delete_type = DeleteType::WhenPackageRemoved as u32 | DeleteType::WhenUserRemoved as u32;
query.insert_attr(Tag::DeleteType, delete_type + 1);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
}
#[test]
fn remove_invalid_label() {
let labels = &[CRITICAL_LABEL_ATTRS, NORMAL_LABEL_ATTRS].concat();
@ -83,6 +65,19 @@ fn remove_invalid_label() {
}
}
#[test]
fn remove_bool_tag_with_unmatched_type() {
let tags = [Tag::RequirePasswordSet, Tag::IsPersistent];
for tag in tags {
let mut query = AssetMap::new();
query.insert_attr(tag, vec![]);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
query.insert_attr(tag, 0);
expect_error_eq(ErrCode::InvalidArgument, asset_sdk::Manager::build().unwrap().remove(&query).unwrap_err());
}
}
#[test]
fn remove_bytes_tag_with_unmatched_type() {
let mut tags_bytes = [CRITICAL_LABEL_ATTRS, NORMAL_LABEL_ATTRS].concat();
@ -99,7 +94,7 @@ fn remove_bytes_tag_with_unmatched_type() {
#[test]
fn remove_number_tag_with_unmatched_type() {
let tags_bytes = [Tag::Accessibility, Tag::AuthType, Tag::SyncType, Tag::DeleteType];
let tags_bytes = [Tag::Accessibility, Tag::AuthType, Tag::SyncType];
for tag in tags_bytes {
let mut query = AssetMap::new();
query.insert_attr(tag, vec![]);

View File

@ -84,26 +84,6 @@ fn update_query_invalid_accessibility() {
);
}
#[test]
fn update_query_required_pwd_with_unmatched_type() {
let function_name = function!().as_bytes();
let mut update = AssetMap::new();
update.insert_attr(Tag::Secret, function_name.to_owned());
let mut query = AssetMap::new();
query.insert_attr(Tag::Alias, function_name.to_owned());
query.insert_attr(Tag::RequirePasswordSet, vec![]);
expect_error_eq(
ErrCode::InvalidArgument,
asset_sdk::Manager::build().unwrap().update(&query, &update).unwrap_err(),
);
query.insert_attr(Tag::RequirePasswordSet, 0);
expect_error_eq(
ErrCode::InvalidArgument,
asset_sdk::Manager::build().unwrap().update(&query, &update).unwrap_err(),
);
}
#[test]
fn update_query_invalid_auth_type() {
let function_name = function!().as_bytes();
@ -139,21 +119,6 @@ fn update_query_invalid_sync_type() {
);
}
#[test]
fn update_query_invalid_delete_type() {
let function_name = function!().as_bytes();
let mut update = AssetMap::new();
update.insert_attr(Tag::Secret, function_name.to_owned());
let mut query = AssetMap::new();
query.insert_attr(Tag::Alias, function_name.to_owned());
let delete_type = DeleteType::WhenPackageRemoved as u32 | DeleteType::WhenUserRemoved as u32;
query.insert_attr(Tag::DeleteType, delete_type + 1);
expect_error_eq(
ErrCode::InvalidArgument,
asset_sdk::Manager::build().unwrap().update(&query, &update).unwrap_err(),
);
}
#[test]
fn update_query_invalid_label() {
let function_name = function!().as_bytes();
@ -177,6 +142,30 @@ fn update_query_invalid_label() {
}
}
#[test]
fn update_query_bool_tag_with_unmatched_type() {
let tags = [Tag::RequirePasswordSet, Tag::IsPersistent];
let function_name = function!().as_bytes();
let mut update = AssetMap::new();
update.insert_attr(Tag::Secret, function_name.to_owned());
for tag in tags {
let mut query = AssetMap::new();
query.insert_attr(Tag::Alias, function_name.to_owned());
query.insert_attr(tag, vec![]);
expect_error_eq(
ErrCode::InvalidArgument,
asset_sdk::Manager::build().unwrap().update(&query, &update).unwrap_err(),
);
query.insert_attr(tag, 0);
expect_error_eq(
ErrCode::InvalidArgument,
asset_sdk::Manager::build().unwrap().update(&query, &update).unwrap_err(),
);
}
}
#[test]
fn update_query_bytes_tag_with_unmatched_type() {
let function_name = function!().as_bytes();
@ -206,7 +195,7 @@ fn update_query_number_tag_with_unmatched_type() {
let function_name = function!().as_bytes();
let mut update = AssetMap::new();
update.insert_attr(Tag::Secret, function_name.to_owned());
let tags_num = [Tag::Accessibility, Tag::AuthType, Tag::SyncType, Tag::DeleteType];
let tags_num = [Tag::Accessibility, Tag::AuthType, Tag::SyncType];
for tag in tags_num {
let mut query = AssetMap::new();
query.insert_attr(Tag::Alias, function_name.to_owned());
@ -363,7 +352,7 @@ fn update_unsupported_tags() {
Tag::Accessibility,
Tag::AuthType,
Tag::SyncType,
Tag::DeleteType,
Tag::IsPersistent,
Tag::RequirePasswordSet,
Tag::AuthValidityPeriod,
Tag::ConflictResolution,

View File

@ -65,7 +65,7 @@ HWTEST_F(AssetRemoveTest, AssetRemoveTest001, TestSize.Level0)
{ .tag = ASSET_TAG_REQUIRE_PASSWORD_SET, .value.boolean = false },
{ .tag = ASSET_TAG_AUTH_TYPE, .value.u32 = ASSET_AUTH_TYPE_NONE },
{ .tag = ASSET_TAG_SYNC_TYPE, .value.u32 = ASSET_SYNC_TYPE_NEVER },
{ .tag = ASSET_TAG_DELETE_TYPE, .value.u32 = ASSET_DELETE_WHEN_PACKAGE_REMOVED },
{ .tag = ASSET_TAG_IS_PERSISTENT, .value.boolean = false },
{ .tag = ASSET_TAG_DATA_LABEL_NORMAL_1, .value.blob = funcName },
{ .tag = ASSET_TAG_DATA_LABEL_NORMAL_2, .value.blob = funcName },
{ .tag = ASSET_TAG_DATA_LABEL_NORMAL_3, .value.blob = funcName },
@ -82,7 +82,7 @@ HWTEST_F(AssetRemoveTest, AssetRemoveTest001, TestSize.Level0)
{ .tag = ASSET_TAG_REQUIRE_PASSWORD_SET, .value.boolean = false },
{ .tag = ASSET_TAG_AUTH_TYPE, .value.u32 = ASSET_AUTH_TYPE_NONE },
{ .tag = ASSET_TAG_SYNC_TYPE, .value.u32 = ASSET_SYNC_TYPE_NEVER },
{ .tag = ASSET_TAG_DELETE_TYPE, .value.u32 = ASSET_DELETE_WHEN_PACKAGE_REMOVED },
{ .tag = ASSET_TAG_IS_PERSISTENT, .value.boolean = false },
{ .tag = ASSET_TAG_DATA_LABEL_NORMAL_1, .value.blob = funcName },
{ .tag = ASSET_TAG_DATA_LABEL_NORMAL_2, .value.blob = funcName },
{ .tag = ASSET_TAG_DATA_LABEL_NORMAL_3, .value.blob = funcName },
@ -133,7 +133,7 @@ HWTEST_F(AssetRemoveTest, AssetRemoveTest002, TestSize.Level0)
*/
HWTEST_F(AssetRemoveTest, AssetRemoveTest003, TestSize.Level0)
{
int arr[] = { ASSET_TAG_ACCESSIBILITY, ASSET_TAG_AUTH_TYPE, ASSET_TAG_SYNC_TYPE, ASSET_TAG_DELETE_TYPE };
int arr[] = { ASSET_TAG_ACCESSIBILITY, ASSET_TAG_AUTH_TYPE, ASSET_TAG_SYNC_TYPE, ASSET_TAG_IS_PERSISTENT };
for (int i = 0; i < ARRAY_SIZE(arr); i++) {
Asset_Blob tmpBlob = { .size = strlen(__func__), .data = nullptr };
Asset_Attr attr[] = {