use super::{
Certificate, HashTree, LookupResult, SubtreeLookupResult,
cbor::strict::{DecodeError, DecodeLimits, decode_certificate},
signature::{RootKey, authenticate_certificate as verify_signature},
};
use crate::{Principal, canister_sig_creation::extract_raw_root_pk_from_der};
use ic_certification::HashTreeNode;
mod ranges;
#[derive(Clone, Copy, Debug)]
pub struct Limits {
pub certificate_bytes: usize,
pub delegation_bytes: usize,
pub tree_nodes: usize,
pub tree_depth: usize,
pub canister_ranges: usize,
}
#[derive(Clone, Copy, Debug)]
pub struct TimeWindow {
pub reference_ns: u64,
pub max_age_ns: u64,
pub max_future_skew_ns: u64,
}
impl TimeWindow {
fn bounds(self) -> Result<(u64, u64), Error> {
Ok((
self.reference_ns
.checked_sub(self.max_age_ns)
.ok_or(Error::InvalidWindow)?,
self.reference_ns
.checked_add(self.max_future_skew_ns)
.ok_or(Error::InvalidWindow)?,
))
}
}
#[derive(Clone, Copy, Debug)]
pub struct TimePolicy {
pub certificate: TimeWindow,
pub delegation: TimeWindow,
}
#[derive(Debug)]
pub struct AuthenticatedCertificate {
pub certificate: Certificate,
pub time_ns: u64,
pub delegation_time_ns: Option<u64>,
}
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("invalid certificate encoding: {0}")]
Decode(#[source] DecodeError),
#[error("certificate tree exceeds traversal allowance")]
TreeLimit,
#[error("ambiguous certificate tree")]
InvalidTree,
#[error("invalid historical time window")]
InvalidWindow,
#[error("invalid certificate time")]
InvalidTime,
#[error("certificate time is outside the admitted historical window")]
TimeOutsideWindow,
#[error("invalid certificate public-key envelope")]
InvalidKey,
#[error("certificate signature verification failed")]
Signature,
#[error("invalid certificate delegation")]
InvalidDelegation,
#[error("required certified delegation path is unavailable")]
MissingDelegationPath,
#[error("invalid certified canister ranges")]
InvalidRanges,
#[error("certified canister ranges exceed allowance")]
RangeLimit,
#[error("certificate is not authorized for the effective canister")]
NotAuthorized,
}
pub fn authenticate_certificate_at(
bytes: &[u8],
root_key_der: &[u8],
effective_canister: Principal,
time: TimePolicy,
limits: Limits,
) -> Result<AuthenticatedCertificate, Error> {
let signing_window = time.certificate.bounds()?;
let delegation_window = time.delegation.bounds()?;
let certificate = decode_certificate(
bytes,
DecodeLimits {
bytes: limits.certificate_bytes,
},
)
.map_err(Error::Decode)?;
let mut nodes = limits.tree_nodes;
admit_tree(&certificate.tree, &mut nodes, limits.tree_depth)?;
let root = extract_raw_root_pk_from_der(root_key_der).map_err(|_| Error::InvalidKey)?;
let delegation_time_ns = if let Some(delegation) = &certificate.delegation {
Principal::try_from_slice(&delegation.subnet_id).map_err(|_| Error::InvalidDelegation)?;
let authority = decode_certificate(
&delegation.certificate,
DecodeLimits {
bytes: limits.delegation_bytes,
},
)
.map_err(Error::Decode)?;
if authority.delegation.is_some() {
return Err(Error::InvalidDelegation);
}
admit_tree(&authority.tree, &mut nodes, limits.tree_depth)?;
verify_signature(&authority, RootKey::Raw(&root)).map_err(|()| Error::Signature)?;
let authority_time = checked_time(&authority.tree, delegation_window)?;
authorize(
&authority.tree,
&delegation.subnet_id,
effective_canister,
limits.canister_ranges,
)?;
let key = required_leaf(
&authority.tree,
&[b"subnet", &delegation.subnet_id, b"public_key"],
)?;
let key = extract_raw_root_pk_from_der(key).map_err(|_| Error::InvalidKey)?;
verify_signature(&certificate, RootKey::Raw(&key)).map_err(|()| Error::Signature)?;
Some(authority_time)
} else {
verify_signature(&certificate, RootKey::Raw(&root)).map_err(|()| Error::Signature)?;
None
};
let time_ns = checked_time(&certificate.tree, signing_window)?;
Ok(AuthenticatedCertificate {
certificate,
time_ns,
delegation_time_ns,
})
}
fn checked_time(tree: &HashTree, window: (u64, u64)) -> Result<u64, Error> {
let LookupResult::Found(bytes) = tree.lookup_path([b"time".as_slice()]) else {
return Err(Error::InvalidTime);
};
if bytes.is_empty() || bytes.len() > 10 {
return Err(Error::InvalidTime);
}
let mut time = 0;
for (i, &byte) in bytes.iter().enumerate() {
if i == 9 && byte > 1 {
return Err(Error::InvalidTime);
}
time |= u64::from(byte & 127) << (i * 7);
if byte & 128 == 0 {
if i + 1 != bytes.len() {
return Err(Error::InvalidTime);
}
return if window.0 <= time && time <= window.1 {
Ok(time)
} else {
Err(Error::TimeOutsideWindow)
};
}
}
Err(Error::InvalidTime)
}
fn admit_tree(tree: &HashTree, nodes: &mut usize, depth: usize) -> Result<(), Error> {
forest(tree.as_ref(), nodes, depth, &mut None, &mut false)
}
fn forest<'a>(
node: &'a HashTreeNode,
nodes: &mut usize,
depth: usize,
previous: &mut Option<&'a [u8]>,
value: &mut bool,
) -> Result<(), Error> {
*nodes = nodes.checked_sub(1).ok_or(Error::TreeLimit)?;
let next_depth = depth.checked_sub(1).ok_or(Error::TreeLimit)?;
match node {
HashTreeNode::Fork(children) => {
forest(&children.0, nodes, next_depth, previous, value)?;
forest(&children.1, nodes, next_depth, previous, value)
}
HashTreeNode::Labeled(label, child) => {
let label = label.as_bytes();
if *value || previous.is_some_and(|old| old >= label) {
return Err(Error::InvalidTree);
}
*previous = Some(label);
forest(child, nodes, next_depth, &mut None, &mut false)
}
HashTreeNode::Leaf(_) => {
if *value || previous.is_some() {
return Err(Error::InvalidTree);
}
*value = true;
Ok(())
}
HashTreeNode::Empty() | HashTreeNode::Pruned(_) => Ok(()),
}
}
fn required_leaf<'a>(tree: &'a HashTree, path: &[&[u8]]) -> Result<&'a [u8], Error> {
match tree.lookup_path(path.iter().copied()) {
LookupResult::Found(bytes) => Ok(bytes),
_ => Err(Error::MissingDelegationPath),
}
}
fn authorize(
tree: &HashTree,
subnet: &[u8],
canister: Principal,
maximum: usize,
) -> Result<(), Error> {
let bytes = match tree.lookup_subtree([b"canister_ranges".as_slice(), subnet]) {
SubtreeLookupResult::Found(shards) => {
match selected_shard(shards.as_ref(), canister.as_slice()) {
Some(HashTreeNode::Leaf(bytes)) => {
return ranges::authorize(bytes, canister, maximum);
}
_ => return Err(Error::NotAuthorized),
}
}
SubtreeLookupResult::Absent | SubtreeLookupResult::Unknown => {
required_leaf(tree, &[b"subnet", subnet, b"canister_ranges"])?
}
};
ranges::authorize(bytes, canister, maximum)
}
fn selected_shard<'a>(node: &'a HashTreeNode, canister: &[u8]) -> Option<&'a HashTreeNode> {
match node {
HashTreeNode::Fork(children) => {
selected_shard(&children.1, canister).or_else(|| selected_shard(&children.0, canister))
}
HashTreeNode::Labeled(label, child) if label.as_bytes() <= canister => Some(child.as_ref()),
_ => None,
}
}