use crate::claims::{ClaimsError, validate_grants, write_grants};
use ic_auth_protocol_types::{
DelegationCertificate, DelegationLeaf, IssuerDelegation, Principal, RootBatchHeader,
};
use sha2::{Digest, Sha256};
use std::{error::Error, fmt};
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DelegationEncodingError {
Grants(ClaimsError),
KeyNameTooLong,
DerivationPathTooLarge,
}
impl fmt::Display for DelegationEncodingError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Grants(error) => write!(f, "invalid delegation grants: {error}"),
Self::KeyNameTooLong => f.write_str("root key name exceeds 128 bytes"),
Self::DerivationPathTooLarge => f.write_str("root derivation path exceeds its bounds"),
}
}
}
impl Error for DelegationEncodingError {}
pub fn certificate_bytes(cert: &DelegationCertificate) -> Result<Vec<u8>, DelegationEncodingError> {
validate_grants(&cert.delegation.grants).map_err(DelegationEncodingError::Grants)?;
let mut bytes = Vec::new();
write_certificate(cert, &mut |part| bytes.extend_from_slice(part));
Ok(bytes)
}
pub fn certificate_hash(cert: &DelegationCertificate) -> Result<[u8; 32], DelegationEncodingError> {
validate_grants(&cert.delegation.grants).map_err(DelegationEncodingError::Grants)?;
let mut hash = Sha256::new();
write_certificate(cert, &mut |part| hash.update(part));
Ok(hash.finalize().into())
}
#[must_use]
pub fn issuer_binding_hash(issuer: Principal, seed_hash: [u8; 32]) -> [u8; 32] {
let mut hash = Sha256::new();
hash.update(b"canic-issuer-proof-binding-v1");
write_principal(issuer, &mut |part| hash.update(part));
hash.update([1, 1]); hash.update(seed_hash);
hash.finalize().into()
}
pub fn delegation_leaf_hash(leaf: &DelegationLeaf) -> Result<[u8; 32], DelegationEncodingError> {
validate_grants(&leaf.delegation.grants).map_err(DelegationEncodingError::Grants)?;
Ok(framed_hash(
b"\0CANIC_ROOT_DELEGATION_CHAIN_KEY_ISSUER_LEAF_V1",
|emit| {
let d = &leaf.delegation;
write_principal(d.root, emit);
write_principal(d.issuer, emit);
emit(&leaf.proof_epoch.to_be_bytes());
write_binding(d, emit);
emit(&d.max_token_ttl_ns.to_be_bytes());
write_audience_grants(d, emit);
emit(&d.not_before_ns.to_be_bytes());
emit(&d.expires_at_ns.to_be_bytes());
emit(&leaf.registry_epoch.to_be_bytes());
emit(&leaf.registry_hash);
},
))
}
pub fn batch_header_hash(header: &RootBatchHeader) -> Result<[u8; 32], DelegationEncodingError> {
if header.key_name.len() > 128 {
return Err(DelegationEncodingError::KeyNameTooLong);
}
Ok(framed_hash(
b"CANIC_ROOT_DELEGATION_CHAIN_KEY_BATCH_V1",
|emit| {
emit(&header.schema_version.to_be_bytes());
write_principal(header.root, emit);
emit(&header.batch_id);
emit(&header.proof_epoch.to_be_bytes());
emit(&header.registry_epoch.to_be_bytes());
emit(&header.registry_hash);
emit(&header.tree_root);
emit(&header.not_before_ns.to_be_bytes());
emit(&header.expires_at_ns.to_be_bytes());
emit(&[1]); write_bytes(header.key_name.as_bytes(), emit);
emit(&header.derivation_path_hash);
emit(&header.key_version.to_be_bytes());
},
))
}
pub fn derivation_path_hash(path: &[Vec<u8>]) -> Result<[u8; 32], DelegationEncodingError> {
if path.len() > 32 || path.iter().any(|part| part.len() > 256) {
return Err(DelegationEncodingError::DerivationPathTooLarge);
}
let mut hash = Sha256::new();
hash.update(b"CANIC_ROOT_DELEGATION_CHAIN_KEY_DERIVATION_PATH_V1");
hash.update((path.len() as u32).to_be_bytes());
for part in path {
write_bytes(part, &mut |part| hash.update(part));
}
Ok(hash.finalize().into())
}
fn write_certificate(cert: &DelegationCertificate, emit: &mut dyn FnMut(&[u8])) {
let d = &cert.delegation;
emit(b"CANIC-AUTH\0\x01");
write_principal(d.root, emit);
write_principal(d.issuer, emit);
write_binding(d, emit);
emit(&cert.issued_at_ns.to_be_bytes());
emit(&d.not_before_ns.to_be_bytes());
emit(&d.expires_at_ns.to_be_bytes());
emit(&d.max_token_ttl_ns.to_be_bytes());
write_audience_grants(d, emit);
}
fn write_binding(d: &IssuerDelegation, emit: &mut dyn FnMut(&[u8])) {
emit(&[1]);
emit(&d.binding_hash);
emit(&[1]);
emit(&d.seed_hash);
}
fn write_audience_grants(d: &IssuerDelegation, emit: &mut dyn FnMut(&[u8])) {
emit(&[1]); emit(d.audience.canonical_network_id.as_bytes());
emit(d.audience.application_id.as_bytes());
write_grants(&d.grants, emit);
}
fn write_principal(value: Principal, emit: &mut dyn FnMut(&[u8])) {
write_bytes(value.as_slice(), emit);
}
fn write_bytes(value: &[u8], emit: &mut dyn FnMut(&[u8])) {
emit(&(value.len() as u32).to_be_bytes());
emit(value);
}
fn framed_hash(domain: &[u8], write: impl Fn(&mut dyn FnMut(&[u8]))) -> [u8; 32] {
let mut length = 0u32;
write(&mut |part| length += part.len() as u32);
let mut hash = Sha256::new();
hash.update(domain);
hash.update(length.to_be_bytes());
write(&mut |part| hash.update(part));
hash.finalize().into()
}