ic-platform 0.33.6

Controlled Candid and IC runtime dependency boundary
Documentation
//! Bounded, effect-free authentication against an explicit historical time policy.
//!
//! Acceptance proves authenticity at the supplied window, never current authority
//! or freshness. Callers retain original roots, effective canisters, bytes, request
//! paths and application policy. No clock, Agent, transport or acceptance cache is used.

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;

/// Caller-selected bounds, with no implicit allocation quota.
#[derive(Clone, Copy, Debug)]
pub struct Limits {
    /// Complete outer certificate byte allowance, checked before decoding.
    pub certificate_bytes: usize,
    /// Embedded delegation certificate allowance, checked before its decoding.
    pub delegation_bytes: usize,
    /// Combined nodes in both trees, checked before hashing or path lookup.
    pub tree_nodes: usize,
    /// Maximum tree depth, counting the root as one, checked before hashing/lookup.
    pub tree_depth: usize,
    /// Maximum pairs parsed in the selected certified canister-range leaf.
    pub canister_ranges: usize,
}

/// An inclusive window around an original reference time, in Unix nanoseconds.
#[derive(Clone, Copy, Debug)]
pub struct TimeWindow {
    /// The caller's original admitted reference time; never read from the clock.
    pub reference_ns: u64,
    /// Largest admitted age relative to the reference.
    pub max_age_ns: u64,
    /// Largest admitted future skew relative to the reference.
    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)?,
        ))
    }
}

/// Separate explicit windows for the signing and root-delegation certificates.
/// Delegations can be older than signing certificates; no age is chosen here.
#[derive(Clone, Copy, Debug)]
pub struct TimePolicy {
    /// Admitted signing-certificate time.
    pub certificate: TimeWindow,
    /// Admitted delegation time, if a delegation is present.
    pub delegation: TimeWindow,
}

/// Authenticated original evidence, without application request-status acceptance.
#[derive(Debug)]
pub struct AuthenticatedCertificate {
    /// Original certificate/tree with the same upstream identity as Agent.
    pub certificate: Certificate,
    /// Authenticated signing-certificate time, in Unix nanoseconds.
    pub time_ns: u64,
    /// Authenticated delegation time, when a delegation was required.
    pub delegation_time_ns: Option<u64>,
}

/// A refused historical authentication; partial evidence is never returned.
#[derive(Debug, thiserror::Error)]
pub enum Error {
    /// Strict CBOR grammar, field, duplicate, trailing or input-byte admission failed.
    #[error("invalid certificate encoding: {0}")]
    Decode(#[source] DecodeError),
    /// The combined tree-node or tree-depth allowance was exhausted.
    #[error("certificate tree exceeds traversal allowance")]
    TreeLimit,
    /// Sibling labels are repeated/out of order or leaves have ambiguous siblings.
    #[error("ambiguous certificate tree")]
    InvalidTree,
    /// The reference/window arithmetic overflowed or underflowed.
    #[error("invalid historical time window")]
    InvalidWindow,
    /// No unique, complete unsigned u64 LEB128 time was authenticated.
    #[error("invalid certificate time")]
    InvalidTime,
    /// The signing or delegation timestamp lies outside its inclusive window.
    #[error("certificate time is outside the admitted historical window")]
    TimeOutsideWindow,
    /// A root/subnet key has invalid DER framing.
    #[error("invalid certificate public-key envelope")]
    InvalidKey,
    /// Checked BLS verification failed, including identity-key refusal.
    #[error("certificate signature verification failed")]
    Signature,
    /// More than one delegation or an invalid subnet identifier was supplied.
    #[error("invalid certificate delegation")]
    InvalidDelegation,
    /// A required certified key/range leaf was absent, pruned or not a leaf.
    #[error("required certified delegation path is unavailable")]
    MissingDelegationPath,
    /// The selected certified range leaf has malformed/trailing CBOR or invalid pairs.
    #[error("invalid certified canister ranges")]
    InvalidRanges,
    /// The caller's maximum certified range count was exhausted.
    #[error("certified canister ranges exceed allowance")]
    RangeLimit,
    /// The effective canister is outside the delegated authority.
    #[error("certificate is not authorized for the effective canister")]
    NotAuthorized,
}

/// Authenticate original certificate bytes using the original root and time policy.
///
/// Root/subnet keys use exact IC DER framing and checked external BLS primitives.
/// Exactly one delegation is supported, with legacy or sharded certified ranges.
/// Every visible tree has ordered, unique sibling labels. Strict decoding retains
/// its built-in CBOR recursion limit; input bounds are not allocation quotas.
/// Both trees are admitted against the combined node/depth bounds before digesting
/// or lookup, and every pair in the selected range leaf is validated even on a match.
///
/// The root is authoritative without delegation, as in the live verifier. Callers
/// must still bind the exact original request-status path and reply/rejection.
///
/// # Errors
/// Refuses invalid windows, bounded/strict decoding, ambiguous trees/times, invalid
/// keys/signatures/delegations, unavailable authority and out-of-window times.
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,
    }
}