use core::marker::PhantomData;
use core::ops::Deref;
pub use generic_array::GenericArray;
pub use heapless::{
String,
Vec,
};
pub use crate::Bytes;
pub use littlefs2::{
fs::{DirEntry, Filesystem},
driver::Storage as LfsStorage,
io::Result as LfsResult,
path::PathBuf,
};
use rand_core::{CryptoRng, RngCore};
use serde::{Deserialize, Serialize};
use crate::config::*;
use crate::key::Secrecy;
pub use crate::platform::Platform;
pub use crate::client::FutureResult;
#[derive(Copy, Clone, PartialEq, PartialOrd)]
pub struct Id(pub(crate) u128);
impl Eq for Id {}
impl core::fmt::Debug for Id {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(f, "Id(")?;
for ch in &self.hex() {
write!(f, "{}", &(*ch as char))?;
}
write!(f, ")")
}
}
pub type SpecialId = u8;
pub trait ObjectId: Deref<Target = Id> {}
impl Id {
pub(crate) fn new(rng: &mut (impl CryptoRng + RngCore)) -> Self {
let mut id = [0u8; 16];
rng.fill_bytes(&mut id);
Self(u128::from_be_bytes(id))
}
pub fn is_special(&self) -> bool {
self.0 < 256
}
pub fn hex(&self) -> Bytes<32> {
const HEX_CHARS: &[u8] = b"0123456789abcdef";
let mut buffer = Bytes::new();
let array = self.0.to_be_bytes();
for i in 0 .. array.len() {
if array[i] == 0 && i != (array.len() - 1) {
continue;
}
buffer.push(HEX_CHARS[(array[i] >> 4) as usize]).unwrap();
buffer.push(HEX_CHARS[(array[i] & 0xf) as usize]).unwrap();
}
buffer
}
}
macro_rules! impl_id { ($Name:ident) => {
#[derive(Copy, Clone, Debug, serde::Deserialize, PartialEq, PartialOrd, serde::Serialize)]
#[serde(transparent)]
pub struct $Name(pub(crate) Id);
impl Eq for $Name {}
impl ObjectId for $Name {}
impl Deref for $Name {
type Target = Id;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl $Name {
pub fn new(rng: &mut (impl CryptoRng + RngCore)) -> Self {
Self(Id::new(rng))
}
pub const fn from_special(special_id: u8) -> Self {
Self(Id(special_id as _))
}
}
impl From<SpecialId> for $Name {
fn from(id: u8) -> Self {
Self(Id(id as _))
}
}
}}
impl_id!(CertId);
impl_id!(CounterId);
impl_id!(KeyId);
pub mod ui {
use super::*;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Status {
Idle,
WaitingForUserPresence,
Processing,
Error,
}
}
pub mod reboot {
use super::*;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum To {
Application,
ApplicationUpdate,
}
}
pub mod consent {
use super::*;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Level {
None,
Normal,
Strong,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Urgency {
InterruptOthers,
FailIfOthers,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Error {
FailedToInterrupt,
Interrupted,
TimedOut,
TimeoutNotImplemented,
}
pub type Result = core::result::Result<(), Error>;
}
pub type ClientId = PathBuf;
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
#[allow(clippy::large_enum_variant)]
pub enum Attributes {
Certificate,
Counter,
Data(DataAttributes),
Key(KeyAttributes),
}
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum CertificateType {
PublicKey,
Attribute,
}
#[derive(Clone, Default, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub struct DataAttributes {
pub kind: ShortData,
pub value: LongData,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub struct KeyAttributes {
sensitive: bool,
extractable: bool,
persistent: bool,
}
impl Default for KeyAttributes {
fn default() -> Self {
Self {
sensitive: true,
extractable: false,
persistent: false,
}
}
}
impl KeyAttributes {
pub fn new() -> Self {
Default::default()
}
}
#[derive(Clone, Default, Eq, PartialEq, Debug, Deserialize, Serialize)]
#[non_exhaustive]
pub struct Letters(pub ShortData);
impl TryFrom<ShortData> for Letters {
type Error = crate::error::Error;
fn try_from(bytes: ShortData) -> Result<Self, Self::Error> {
if !&bytes.iter().all(|b| *b >= b'a' && *b <= b'z') {
return Err(Self::Error::NotJustLetters);
}
Ok(Letters(bytes))
}
}
impl serde::Serialize for Id {
fn serialize<S>(&self, serializer: S) -> core::result::Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.serialize_bytes(&self.0.to_be_bytes())
}
}
impl<'de> serde::Deserialize<'de> for Id {
fn deserialize<D>(deserializer: D) -> core::result::Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
struct ValueVisitor<'de>(PhantomData<&'de ()>);
impl<'de> serde::de::Visitor<'de> for ValueVisitor<'de>
{
type Value = Id;
fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str("16 bytes")
}
fn visit_bytes<E>(self, v: &[u8]) -> core::result::Result<Self::Value, E>
where
E: serde::de::Error,
{
if v.len() != 16 {
return Err(E::invalid_length(v.len(), &self));
}
Ok(Id(u128::from_be_bytes(v.try_into().unwrap())))
}
}
deserializer.deserialize_bytes(ValueVisitor(PhantomData))
}
}
#[derive(Clone, Eq, PartialEq, Debug)]
pub enum ObjectType {
Certificate(CertificateType),
Counter,
Data,
Key(Secrecy),
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct PublicKeyAttributes {
sensitive: bool,
extractable: bool,
persistent: bool,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug)]
pub struct PrivateKeyAttributes {
sensitive: bool,
extractable: bool,
persistent: bool,
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Location {
Volatile,
Internal,
External,
}
#[derive(Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub struct StorageAttributes {
pub persistence: Location,
}
impl StorageAttributes {
pub fn set_persistence(mut self, persistence: Location) -> Self {
self.persistence = persistence;
self
}
}
impl StorageAttributes {
pub fn new() -> Self {
Self {
persistence: Location::Volatile,
}
}
}
impl Default for StorageAttributes {
fn default() -> Self {
Self::new()
}
}
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum Mechanism {
Aes256Cbc,
Chacha8Poly1305,
Ed255,
HmacBlake2s,
HmacSha1,
HmacSha256,
HmacSha512,
P256,
P256Prehashed,
Sha256,
Tdes,
Totp,
Trng,
X255,
}
pub type LongData = Bytes<MAX_LONG_DATA_LENGTH>;
pub type MediumData = Bytes<MAX_MEDIUM_DATA_LENGTH>;
pub type ShortData = Bytes<MAX_SHORT_DATA_LENGTH>;
pub type Message = Bytes<MAX_MESSAGE_LENGTH>;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum KeySerialization {
Cose,
EcdhEsHkdf256,
Raw,
Sec1,
}
pub type Signature = Bytes<MAX_SIGNATURE_LENGTH>;
#[derive(Copy, Clone, Eq, PartialEq, Debug, Serialize, Deserialize)]
pub enum SignatureSerialization {
Asn1Der,
Raw,
}
pub type UserAttribute = Bytes<MAX_USER_ATTRIBUTE_LENGTH>;