mod capacity;
#[cfg(feature = "receiver-stable")]
pub(crate) use capacity::MAX_SESSION_BYTES;
mod login;
#[cfg(feature = "receiver-stable")]
mod logout;
#[cfg(test)]
mod tests;
use crate::{
claims::validate_grants,
grant_policy::{for_role, scopes_subset},
session_request::SessionRequest,
};
use ic_auth_protocol_types::{
AudienceId, AuthRole, DelegatedRoleGrant, PortableMechanism, Principal, ScopeLabel,
};
use std::{error::Error, fmt};
pub(crate) use capacity::{AdmissionFootprint, assess_capacity};
pub use capacity::{SessionCapacity, SessionUsage};
pub use login::LoginLimits;
#[cfg(feature = "receiver-stable")]
pub(crate) use login::check_record;
pub(crate) use login::{LoginDecision, LoginSnapshot, assess_login};
#[cfg(feature = "receiver-stable")]
pub(crate) use logout::plan_logout;
#[cfg(feature = "receiver-stable")]
pub use logout::{LogoutError, LogoutReceipt, UnknownLogoutLimits};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "receiver-stable",
derive(serde::Serialize, serde::Deserialize)
)]
pub struct LoginBinding {
pub issuer: Principal,
pub subject: Principal,
pub device_slot: u8,
pub device_generation: u64,
pub started_at_ns: u64,
pub deadline_ns: u64,
}
#[derive(Clone, Copy, Debug)]
pub struct SessionFacts<'a> {
#[cfg(feature = "receiver-stable")]
pub ext: Option<&'a [u8]>,
pub caller: Principal,
pub audience: AudienceId,
pub login: LoginBinding,
pub mechanism: PortableMechanism,
pub key_binding_id: [u8; 32],
pub role: &'a AuthRole,
pub scopes: &'a [ScopeLabel],
pub authority_generation: u64,
pub established_at_ns: u64,
pub expires_at_ns: u64,
pub fingerprint: [u8; 32],
pub request_hash: [u8; 32],
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(
feature = "receiver-stable",
derive(serde::Serialize, serde::Deserialize)
)]
pub(crate) struct LoginFacts {
pub caller: Principal,
pub audience: AudienceId,
pub binding: Option<LoginBinding>,
pub until_ns: u64,
pub denied: bool,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct DeviceFacts {
pub issuer: Principal,
pub subject: Principal,
pub slot: u8,
pub generation: u64,
pub caller: Principal,
}
#[derive(Clone, Copy, Debug)]
pub(crate) struct ReceiverSnapshot<'a> {
pub audience: AudienceId,
pub authority_generation: u64,
pub observed_at_ns: u64,
pub session: Option<&'a SessionFacts<'a>>,
pub login: Option<&'a LoginFacts>,
pub device: Option<&'a DeviceFacts>,
}
#[derive(Clone, Copy, Debug)]
pub struct SessionAuthority<'a> {
pub caller: Principal,
pub now_ns: u64,
pub audience: AudienceId,
pub issuer: Principal,
pub mechanism: PortableMechanism,
pub key_binding_id: [u8; 32],
pub role: &'a AuthRole,
pub grants: &'a [DelegatedRoleGrant],
pub generation: u64,
pub not_before_ns: u64,
pub expires_at_ns: u64,
pub enrollment_expires_at_ns: u64,
pub min_login_started_at_ns: u64,
pub max_session_ttl_secs: u64,
pub enabled: bool,
pub subject_admissible: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SessionPolicyError {
Disabled,
InvalidContext,
ClockRollback,
InvalidFacts,
Revoked,
MissingOrExpired,
StaleAuthority,
ScopeRejected,
ReplayConflict,
BindingConflict,
Capacity,
ByteCapacity,
}
impl fmt::Display for SessionPolicyError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "receiver policy refused: {self:?}")
}
}
impl Error for SessionPolicyError {}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum RetryDecision {
FreshProofRequired,
ExactRetry {
expires_at_ns: u64,
},
}
#[derive(Clone, Copy)]
pub(crate) struct CheckedAuthority<'a, 'host>(&'a SessionAuthority<'host>);
impl<'a, 'host> CheckedAuthority<'a, 'host> {
pub(crate) fn new(
authority: &'a SessionAuthority<'host>,
audience: AudienceId,
) -> Result<Self, SessionPolicyError> {
check_authority(authority, audience)?;
Ok(Self(authority))
}
}
pub(crate) fn assess_session_checked(
snapshot: &ReceiverSnapshot<'_>,
checked: CheckedAuthority<'_, '_>,
required_scopes: &[ScopeLabel],
) -> Result<(), SessionPolicyError> {
let authority = checked.0;
if required_scopes.len() > 16 {
return Err(SessionPolicyError::InvalidContext);
}
check_snapshot(snapshot, authority)?;
let session = snapshot
.session
.ok_or(SessionPolicyError::MissingOrExpired)?;
check_live(session, snapshot, authority)?;
if !scopes_subset(required_scopes, session.scopes) {
return Err(SessionPolicyError::ScopeRejected);
}
Ok(())
}
pub(crate) fn assess_retry_checked(
snapshot: &ReceiverSnapshot<'_>,
checked: CheckedAuthority<'_, '_>,
fingerprint: [u8; 32],
request: &SessionRequest,
replay_consumed: bool,
) -> Result<RetryDecision, SessionPolicyError> {
let authority = checked.0;
check_snapshot(snapshot, authority)?;
if let Some(session) = snapshot.session
&& session.fingerprint == fingerprint
{
if session.request_hash != request.hash() {
return Err(SessionPolicyError::ReplayConflict);
}
check_live(session, snapshot, authority)?;
return Ok(RetryDecision::ExactRetry {
expires_at_ns: session.expires_at_ns,
});
}
if replay_consumed {
return Err(SessionPolicyError::ReplayConflict);
}
Ok(RetryDecision::FreshProofRequired)
}
fn check_snapshot(
s: &ReceiverSnapshot<'_>,
a: &SessionAuthority<'_>,
) -> Result<(), SessionPolicyError> {
if a.audience != s.audience {
return Err(SessionPolicyError::InvalidContext);
}
use SessionPolicyError as E;
if a.now_ns < s.observed_at_ns {
return Err(E::ClockRollback);
}
if let Some(login) = s.login {
if login.caller != a.caller || login.audience != s.audience || login.until_ns == 0 {
return Err(E::InvalidFacts);
}
if login.denied && a.now_ns < login.until_ns {
return Err(E::Revoked);
}
}
if s.authority_generation != a.generation {
return Err(E::StaleAuthority);
}
Ok(())
}
pub(crate) fn check_authority(
a: &SessionAuthority<'_>,
audience: AudienceId,
) -> Result<(), SessionPolicyError> {
use SessionPolicyError as E;
if !a.enabled || !a.subject_admissible {
return Err(E::Disabled);
}
if !login_caller(a.caller)
|| a.issuer == Principal::anonymous()
|| a.audience != audience
|| a.not_before_ns >= a.expires_at_ns
|| a.enrollment_expires_at_ns == 0
|| !(1..=1800).contains(&a.max_session_ttl_secs)
|| validate_grants(a.grants).is_err()
{
return Err(E::InvalidContext);
}
Ok(())
}
pub(crate) fn check_session_shape(s: &SessionFacts<'_>) -> Result<(), SessionPolicyError> {
let b = s.login;
if !(1..=16).contains(&s.scopes.len())
|| s.scopes.windows(2).any(|pair| pair[0] >= pair[1])
|| !valid_binding(b)
|| b.started_at_ns > s.established_at_ns
|| s.established_at_ns >= s.expires_at_ns
|| s.expires_at_ns > b.deadline_ns
|| s.expires_at_ns - s.established_at_ns > 1_800_000_000_000
{
return Err(SessionPolicyError::InvalidFacts);
}
Ok(())
}
fn check_live(
s: &SessionFacts<'_>,
facts: &ReceiverSnapshot<'_>,
a: &SessionAuthority<'_>,
) -> Result<(), SessionPolicyError> {
use SessionPolicyError as E;
let b = s.login;
check_session_shape(s)?;
if a.now_ns < s.established_at_ns || a.now_ns >= s.expires_at_ns {
return Err(E::MissingOrExpired);
}
if s.caller != a.caller
|| s.audience != a.audience
|| b.issuer != a.issuer
|| s.mechanism != a.mechanism
|| s.key_binding_id != a.key_binding_id
|| s.role != a.role
|| s.authority_generation != a.generation
|| b.started_at_ns < a.min_login_started_at_ns
|| a.now_ns < a.not_before_ns
|| a.now_ns >= a.expires_at_ns
|| a.now_ns >= a.enrollment_expires_at_ns
|| s.expires_at_ns > a.expires_at_ns
|| s.expires_at_ns - s.established_at_ns > a.max_session_ttl_secs * 1_000_000_000
{
return Err(E::StaleAuthority);
}
let grant = for_role(a.grants, a.role).ok_or(E::ScopeRejected)?;
if !scopes_subset(s.scopes, &grant.scopes) {
return Err(E::ScopeRejected);
}
let login = facts.login.ok_or(E::InvalidFacts)?;
let device = facts.device.ok_or(E::InvalidFacts)?;
if login.denied
|| login.until_ns < b.deadline_ns
|| login.until_ns <= a.now_ns
|| login.binding != Some(b)
|| device.issuer != b.issuer
|| device.subject != b.subject
|| device.slot != b.device_slot
|| device.generation != b.device_generation
|| device.caller != s.caller
{
return Err(E::InvalidFacts);
}
Ok(())
}
pub(crate) fn login_caller(caller: Principal) -> bool {
let bytes = caller.as_slice();
bytes.len() == 29 && bytes[28] == 2
}
fn valid_binding(binding: LoginBinding) -> bool {
binding.issuer != Principal::anonymous()
&& binding.subject != Principal::anonymous()
&& binding.device_slot < 8
&& binding.device_generation != 0
&& binding
.deadline_ns
.checked_sub(binding.started_at_ns)
.is_some_and(|ttl| ttl > 0 && ttl <= 90 * 86_400_000_000_000)
}