diff --git a/src/error.rs b/src/error.rs index 076178e..d9ae575 100644 --- a/src/error.rs +++ b/src/error.rs @@ -4,6 +4,8 @@ use thiserror::Error; pub enum Error { #[error("ikm error: no input key material available")] IkmNoneAvailable, + #[error("ikm error: {0}: input key material not found")] + IkmNotFound(u32), #[error("parsing error: invalid base64-urlsafe-nopadding data: {0}")] ParsingBase64Error(base64ct::Error), #[error("parsing error: invalid data length: {0} bytes")] diff --git a/src/ikm.rs b/src/ikm.rs index 32c1571..0f368d5 100644 --- a/src/ikm.rs +++ b/src/ikm.rs @@ -128,6 +128,14 @@ impl InputKeyMaterialList { .find(|&ikm| !ikm.is_revoked && ikm.created_at < SystemTime::now()) .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)] @@ -277,4 +285,30 @@ mod tests { let latest_ikm = res.unwrap(); 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()); + } }