use noxtls_core::{Error, Result};
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum PsaResultCode {
Success,
InvalidArgument,
NotPermitted,
InvalidHandle,
BufferTooSmall,
NotSupported,
InvalidSignature,
GenericError,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PsaError {
pub code: PsaResultCode,
pub detail_status: Option<i32>,
}
impl PsaError {
pub fn new(code: PsaResultCode, detail_status: Option<i32>) -> Self {
Self {
code,
detail_status,
}
}
pub fn to_noxtls_error(&self) -> Error {
match self.code {
PsaResultCode::Success => Error::CryptoFailure("psa success mapped as error"),
PsaResultCode::InvalidArgument => Error::ParseFailure("psa invalid argument"),
PsaResultCode::NotPermitted => Error::StateError("psa operation not permitted"),
PsaResultCode::InvalidHandle => Error::StateError("psa key handle invalid"),
PsaResultCode::BufferTooSmall => Error::InvalidLength("psa buffer too small"),
PsaResultCode::NotSupported => Error::UnsupportedFeature("psa capability unavailable"),
PsaResultCode::InvalidSignature => {
Error::CryptoFailure("psa cryptographic operation failed")
}
PsaResultCode::GenericError => Error::CryptoFailure("psa backend failure"),
}
}
}
pub fn normalize_psa_status(status: i32) -> PsaResultCode {
match status {
0 => PsaResultCode::Success,
-133 => PsaResultCode::NotPermitted,
-134 => PsaResultCode::InvalidArgument,
-136 => PsaResultCode::InvalidHandle,
-138 => PsaResultCode::BufferTooSmall,
-1344 => PsaResultCode::InvalidSignature,
-1345 => PsaResultCode::NotSupported,
_ => PsaResultCode::GenericError,
}
}
pub fn map_status_to_result(status: i32) -> Result<()> {
let normalized = normalize_psa_status(status);
if normalized == PsaResultCode::Success {
Ok(())
} else {
Err(PsaError::new(normalized, Some(status)).to_noxtls_error())
}
}