use tls_codec::{TlsSerialize, TlsSize};
use super::{Deserialize, LifetimeExtensionError, Serialize};
use std::io::Read;
use std::time::{SystemTime, UNIX_EPOCH};
const DEFAULT_KEY_PACKAGE_LIFETIME: u64 = 60 * 60 * 24 * 28 * 3; const DEFAULT_KEY_PACKAGE_LIFETIME_MARGIN: u64 = 60 * 60;
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, TlsSerialize, TlsSize)]
pub struct LifetimeExtension {
not_before: u64,
not_after: u64,
}
impl LifetimeExtension {
pub fn new(t: u64) -> Self {
let lifetime_margin: u64 = DEFAULT_KEY_PACKAGE_LIFETIME_MARGIN;
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!")
.as_secs();
let not_before = now - lifetime_margin;
let not_after = now + t;
Self {
not_before,
not_after,
}
}
pub(crate) fn is_valid(&self) -> bool {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.expect("SystemTime before UNIX EPOCH!")
.as_secs();
self.not_before < now && now < self.not_after
}
}
impl Default for LifetimeExtension {
fn default() -> Self {
LifetimeExtension::new(DEFAULT_KEY_PACKAGE_LIFETIME)
}
}
impl tls_codec::Deserialize for LifetimeExtension {
fn tls_deserialize<R: Read>(bytes: &mut R) -> Result<Self, tls_codec::Error> {
let not_before = u64::tls_deserialize(bytes)?;
let not_after = u64::tls_deserialize(bytes)?;
let out = Self {
not_before,
not_after,
};
if !out.is_valid() {
log::trace!(
"Lifetime expired!\n\tnot before: {:?} - not_after: {:?}",
not_before,
not_after
);
return Err(tls_codec::Error::DecodingError(format!(
"{:?}",
LifetimeExtensionError::Invalid
)));
}
Ok(out)
}
}