use super::{LoginFacts, login, login_caller};
use ic_auth_protocol_types::{AudienceId, Principal};
use std::{error::Error, fmt};
#[derive(Clone, Copy, Debug)]
#[cfg_attr(
feature = "receiver-stable",
derive(serde::Serialize, serde::Deserialize, Eq, PartialEq)
)]
pub struct UnknownLogoutLimits {
pub max_denials: usize,
pub capacity: u32,
pub refill_interval_ns: u64,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LogoutReceipt {
Revoked {
deny_until_ns: u64,
},
Unconfirmed {
deny_until_ns: u64,
},
}
impl LogoutReceipt {
#[must_use]
pub const fn deny_until_ns(self) -> u64 {
match self {
Self::Revoked { deny_until_ns } | Self::Unconfirmed { deny_until_ns } => deny_until_ns,
}
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum LogoutError {
InvalidCaller,
Capacity,
Clock,
Closed,
InvalidFacts,
}
impl fmt::Display for LogoutError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "logout refused: {self:?}")
}
}
impl Error for LogoutError {}
pub(crate) struct LogoutPlan {
pub(crate) receipt: LogoutReceipt,
pub(crate) charge_unknown: bool,
}
pub(crate) fn plan_logout(
caller: Principal,
audience: AudienceId,
previous: Option<&LoginFacts>,
now_ns: u64,
retention_ns: u64,
unknown_pool: (usize, usize),
) -> Result<LogoutPlan, LogoutError> {
if !login_caller(caller) {
return Err(LogoutError::InvalidCaller);
}
if let Some(old) = previous {
login::check_record(old, audience).map_err(|_| LogoutError::InvalidFacts)?;
if old.caller != caller {
return Err(LogoutError::InvalidFacts);
}
if old.binding.is_some() {
return Ok(LogoutPlan {
receipt: LogoutReceipt::Revoked {
deny_until_ns: old.until_ns,
},
charge_unknown: false,
});
}
if now_ns < old.until_ns {
return Ok(LogoutPlan {
receipt: LogoutReceipt::Unconfirmed {
deny_until_ns: old.until_ns,
},
charge_unknown: false,
});
}
}
let deny_until_ns = now_ns.checked_add(retention_ns).ok_or(LogoutError::Clock)?;
if previous.is_none() && unknown_pool.0 >= unknown_pool.1 {
return Err(LogoutError::Capacity);
}
Ok(LogoutPlan {
receipt: LogoutReceipt::Unconfirmed { deny_until_ns },
charge_unknown: true,
})
}