Skip to main content

ic_auth/
delegation_encoding.rs

1//! Bounded signing commitments for the current root-delegation profile.
2//!
3//! These operations establish canonical bytes only. They verify no signature,
4//! issuer binding, grant authority, schema support, validity window or enrollment.
5//! Certificate issue time is hashed but is absent from the root-signed leaf.
6
7use crate::claims::{ClaimsError, validate_grants, write_grants};
8use ic_auth_protocol_types::{
9    DelegationCertificate, DelegationLeaf, IssuerDelegation, Principal, RootBatchHeader,
10};
11use sha2::{Digest, Sha256};
12use std::{error::Error, fmt};
13
14/// Bounded structural refusal; never an authentication or authorization result.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16pub enum DelegationEncodingError {
17    /// Delegated grants violate shared role/scope shape or ordering.
18    Grants(ClaimsError),
19    /// Root key name exceeds the transport profile's 128-byte cap.
20    KeyNameTooLong,
21    /// More than 32 derivation components, or a component exceeds 256 bytes.
22    DerivationPathTooLarge,
23}
24impl fmt::Display for DelegationEncodingError {
25    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
26        match self {
27            Self::Grants(error) => write!(f, "invalid delegation grants: {error}"),
28            Self::KeyNameTooLong => f.write_str("root key name exceeds 128 bytes"),
29            Self::DerivationPathTooLarge => f.write_str("root derivation path exceeds its bounds"),
30        }
31    }
32}
33impl Error for DelegationEncodingError {}
34
35/// Encode the current certificate without normalization or implicit binding repair.
36pub fn certificate_bytes(cert: &DelegationCertificate) -> Result<Vec<u8>, DelegationEncodingError> {
37    validate_grants(&cert.delegation.grants).map_err(DelegationEncodingError::Grants)?;
38    let mut bytes = Vec::new();
39    write_certificate(cert, &mut |part| bytes.extend_from_slice(part));
40    Ok(bytes)
41}
42
43/// Hash the exact certificate, including its root-unsigned issuance metadata.
44pub fn certificate_hash(cert: &DelegationCertificate) -> Result<[u8; 32], DelegationEncodingError> {
45    validate_grants(&cert.delegation.grants).map_err(DelegationEncodingError::Grants)?;
46    let mut hash = Sha256::new();
47    write_certificate(cert, &mut |part| hash.update(part));
48    Ok(hash.finalize().into())
49}
50
51/// Hash the IC canister-signature issuer/algorithm/seed commitment.
52#[must_use]
53pub fn issuer_binding_hash(issuer: Principal, seed_hash: [u8; 32]) -> [u8; 32] {
54    let mut hash = Sha256::new();
55    hash.update(b"canic-issuer-proof-binding-v1");
56    write_principal(issuer, &mut |part| hash.update(part));
57    hash.update([1, 1]); // Algorithm, then binding variant: both are IC V1.
58    hash.update(seed_hash);
59    hash.finalize().into()
60}
61
62/// Hash one root issuer leaf with its zero prefix and length-framed domain.
63pub fn delegation_leaf_hash(leaf: &DelegationLeaf) -> Result<[u8; 32], DelegationEncodingError> {
64    validate_grants(&leaf.delegation.grants).map_err(DelegationEncodingError::Grants)?;
65    Ok(framed_hash(
66        b"\0CANIC_ROOT_DELEGATION_CHAIN_KEY_ISSUER_LEAF_V1",
67        |emit| {
68            let d = &leaf.delegation;
69            write_principal(d.root, emit);
70            write_principal(d.issuer, emit);
71            emit(&leaf.proof_epoch.to_be_bytes());
72            write_binding(d, emit);
73            emit(&d.max_token_ttl_ns.to_be_bytes());
74            write_audience_grants(d, emit);
75            emit(&d.not_before_ns.to_be_bytes());
76            emit(&d.expires_at_ns.to_be_bytes());
77            emit(&leaf.registry_epoch.to_be_bytes());
78            emit(&leaf.registry_hash);
79        },
80    ))
81}
82
83/// Hash the root batch's fixed ECDSA/secp256k1 header signing preimage.
84pub fn batch_header_hash(header: &RootBatchHeader) -> Result<[u8; 32], DelegationEncodingError> {
85    if header.key_name.len() > 128 {
86        return Err(DelegationEncodingError::KeyNameTooLong);
87    }
88    Ok(framed_hash(
89        b"CANIC_ROOT_DELEGATION_CHAIN_KEY_BATCH_V1",
90        |emit| {
91            emit(&header.schema_version.to_be_bytes());
92            write_principal(header.root, emit);
93            emit(&header.batch_id);
94            emit(&header.proof_epoch.to_be_bytes());
95            emit(&header.registry_epoch.to_be_bytes());
96            emit(&header.registry_hash);
97            emit(&header.tree_root);
98            emit(&header.not_before_ns.to_be_bytes());
99            emit(&header.expires_at_ns.to_be_bytes());
100            emit(&[1]); // ECDSA/secp256k1.
101            write_bytes(header.key_name.as_bytes(), emit);
102            emit(&header.derivation_path_hash);
103            emit(&header.key_version.to_be_bytes());
104        },
105    ))
106}
107
108/// Hash an ordered bounded path; empty components and an empty path are retained.
109pub fn derivation_path_hash(path: &[Vec<u8>]) -> Result<[u8; 32], DelegationEncodingError> {
110    if path.len() > 32 || path.iter().any(|part| part.len() > 256) {
111        return Err(DelegationEncodingError::DerivationPathTooLarge);
112    }
113    let mut hash = Sha256::new();
114    hash.update(b"CANIC_ROOT_DELEGATION_CHAIN_KEY_DERIVATION_PATH_V1");
115    hash.update((path.len() as u32).to_be_bytes());
116    for part in path {
117        write_bytes(part, &mut |part| hash.update(part));
118    }
119    Ok(hash.finalize().into())
120}
121
122fn write_certificate(cert: &DelegationCertificate, emit: &mut dyn FnMut(&[u8])) {
123    let d = &cert.delegation;
124    emit(b"CANIC-AUTH\0\x01");
125    write_principal(d.root, emit);
126    write_principal(d.issuer, emit);
127    write_binding(d, emit);
128    emit(&cert.issued_at_ns.to_be_bytes());
129    emit(&d.not_before_ns.to_be_bytes());
130    emit(&d.expires_at_ns.to_be_bytes());
131    emit(&d.max_token_ttl_ns.to_be_bytes());
132    write_audience_grants(d, emit);
133}
134
135fn write_binding(d: &IssuerDelegation, emit: &mut dyn FnMut(&[u8])) {
136    emit(&[1]);
137    emit(&d.binding_hash);
138    emit(&[1]);
139    emit(&d.seed_hash);
140}
141
142fn write_audience_grants(d: &IssuerDelegation, emit: &mut dyn FnMut(&[u8])) {
143    emit(&[1]); // Fleet audience.
144    emit(d.audience.canonical_network_id.as_bytes());
145    emit(d.audience.fleet_id.as_bytes());
146    write_grants(&d.grants, emit);
147}
148
149fn write_principal(value: Principal, emit: &mut dyn FnMut(&[u8])) {
150    write_bytes(value.as_slice(), emit);
151}
152
153fn write_bytes(value: &[u8], emit: &mut dyn FnMut(&[u8])) {
154    // Every caller admits field bounds before this private traversal.
155    emit(&(value.len() as u32).to_be_bytes());
156    emit(value);
157}
158
159fn framed_hash(domain: &[u8], write: impl Fn(&mut dyn FnMut(&[u8]))) -> [u8; 32] {
160    // At most 16 roles x 32 scopes x 64-byte labels, or a 128-byte key name;
161    // both admitted layouts fit comfortably within u32 on every supported target.
162    let mut length = 0u32;
163    write(&mut |part| length += part.len() as u32);
164    let mut hash = Sha256::new();
165    hash.update(domain);
166    hash.update(length.to_be_bytes());
167    write(&mut |part| hash.update(part));
168    hash.finalize().into()
169}