Add the get_ikm_by_id method to the IKM

This commit is contained in:
Rodolphe Bréard 2024-02-15 18:38:24 +01:00
parent ba08aa44f9
commit f662e47690
2 changed files with 36 additions and 0 deletions

View file

@ -4,6 +4,8 @@ use thiserror::Error;
pub enum Error { pub enum Error {
#[error("ikm error: no input key material available")] #[error("ikm error: no input key material available")]
IkmNoneAvailable, IkmNoneAvailable,
#[error("ikm error: {0}: input key material not found")]
IkmNotFound(u32),
#[error("parsing error: invalid base64-urlsafe-nopadding data: {0}")] #[error("parsing error: invalid base64-urlsafe-nopadding data: {0}")]
ParsingBase64Error(base64ct::Error), ParsingBase64Error(base64ct::Error),
#[error("parsing error: invalid data length: {0} bytes")] #[error("parsing error: invalid data length: {0} bytes")]

View file

@ -128,6 +128,14 @@ impl InputKeyMaterialList {
.find(|&ikm| !ikm.is_revoked && ikm.created_at < SystemTime::now()) .find(|&ikm| !ikm.is_revoked && ikm.created_at < SystemTime::now())
.ok_or(Error::IkmNoneAvailable) .ok_or(Error::IkmNoneAvailable)
} }
#[cfg(feature = "encryption")]
pub(crate) fn get_ikm_by_id(&self, id: u32) -> Result<&InputKeyMaterial, Error> {
self.ikm_lst
.iter()
.find(|&ikm| ikm.id == id)
.ok_or(Error::IkmNotFound(id))
}
} }
#[cfg(test)] #[cfg(test)]
@ -277,4 +285,30 @@ mod tests {
let latest_ikm = res.unwrap(); let latest_ikm = res.unwrap();
assert_eq!(latest_ikm.id, 3); assert_eq!(latest_ikm.id, 3);
} }
#[test]
#[cfg(feature = "encryption")]
fn get_ikm_by_id() {
let mut lst = InputKeyMaterialList::new();
let _ = lst.add_ikm();
let _ = lst.add_ikm();
let _ = lst.add_ikm();
for i in 1..=3 {
let res = lst.get_ikm_by_id(i);
assert!(res.is_ok());
let latest_ikm = res.unwrap();
assert_eq!(latest_ikm.id, i);
}
}
#[test]
#[cfg(feature = "encryption")]
fn get_ikm_by_id_noexists() {
let mut lst = InputKeyMaterialList::new();
let _ = lst.add_ikm();
let _ = lst.add_ikm();
let _ = lst.add_ikm();
let res = lst.get_ikm_by_id(42);
assert!(res.is_err());
}
} }