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