Skip to main content

ic_auth/canonical/
mod.rs

1//! Canonical signed bytes for Root delegations, proofs and role identities.
2//! Domains and tags are protocol identities, not package branding.
3//! This module does not verify signatures, authority, validity or caller binding.
4
5use ic_auth_protocol_types::*;
6use sha2::{Digest, Sha256};
7use thiserror::Error;
8
9// One field encoder feeds either exact byte output or the maintained SHA-256.
10pub(crate) type Sink<'a> = dyn FnMut(&[u8]) + 'a;
11
12const DOMAIN_SEPARATOR: &[u8] = b"CANIC-AUTH\0";
13const ISSUER_PROOF_BINDING_HASH_DOMAIN: &[u8] = b"canic-issuer-proof-binding-v1";
14const CHAIN_KEY_BATCH_HEADER_DOMAIN: &[u8] = b"CANIC_ROOT_DELEGATION_CHAIN_KEY_BATCH_V1";
15const CHAIN_KEY_DELEGATION_CERT_DOMAIN: &[u8] = b"CANIC_ROOT_DELEGATION_CHAIN_KEY_ISSUER_LEAF_V1";
16const CHAIN_KEY_DERIVATION_PATH_DOMAIN: &[u8] =
17    b"CANIC_ROOT_DELEGATION_CHAIN_KEY_DERIVATION_PATH_V1";
18
19// Domain byte assigned to one delegated-auth canonical payload family.
20#[repr(u8)]
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22enum CanonicalDomain {
23    DelegationCert = 1,
24    DelegationProof = 3,
25    RoleHash = 4,
26}
27
28///
29/// CanonicalAuthError
30///
31/// Typed failure surface for delegated auth canonicalization.
32///
33
34#[derive(Debug, Eq, Error, PartialEq)]
35pub enum CanonicalAuthError {
36    #[error("canonical vector length exceeds u32")]
37    LengthOverflow,
38    #[error(transparent)]
39    Scope(#[from] ScopeLabelError),
40    #[error("delegated auth scopes must be strictly sorted and unique")]
41    NonCanonicalScopes,
42    #[error("delegated auth role grants must be strictly sorted and unique")]
43    NonCanonicalRoles,
44}
45
46/// Hash the canonical delegation certificate; this does not authenticate it.
47pub fn cert_hash(cert: &DelegationCert) -> Result<[u8; 32], CanonicalAuthError> {
48    hash_encoded(&[], false, &|out| encode_cert(out, cert))
49}
50
51/// Hash a certificate together with its complete root proof.
52pub fn proof_hash(proof: &DelegationProof) -> Result<[u8; 32], CanonicalAuthError> {
53    hash_encoded(&[], false, &|out| {
54        out(DOMAIN_SEPARATOR);
55        out(&[CanonicalDomain::DelegationProof as u8]);
56        encode_cert(out, &proof.cert)?;
57        encode_root_proof(out, &proof.root_proof)
58    })
59}
60
61/// Hash a chain-key batch header under its existing signed domain.
62pub fn chain_key_batch_header_hash(
63    header: &ChainKeyBatchHeaderV1,
64) -> Result<[u8; 32], CanonicalAuthError> {
65    hash_encoded(&[CHAIN_KEY_BATCH_HEADER_DOMAIN], true, &|out| {
66        encode_chain_key_batch_header(out, header)
67    })
68}
69
70/// Hash an issuer leaf under the existing chain-key Merkle leaf domain.
71pub fn chain_key_delegation_cert_hash(
72    cert: &ChainKeyDelegationCertV1,
73) -> Result<[u8; 32], CanonicalAuthError> {
74    hash_encoded(&[&[0], CHAIN_KEY_DELEGATION_CERT_DOMAIN], true, &|out| {
75        encode_chain_key_delegation_cert(out, cert)
76    })
77}
78
79/// Hash the exact ordered derivation path under its existing Canic domain.
80/// This binds path bytes; it does not derive a key or establish its authority.
81pub fn chain_key_derivation_path_hash(
82    derivation_path: &[Vec<u8>],
83) -> Result<[u8; 32], CanonicalAuthError> {
84    hash_encoded(&[CHAIN_KEY_DERIVATION_PATH_DOMAIN], false, &|out| {
85        encode_chain_key_derivation_path(out, derivation_path)
86    })
87}
88
89/// Bind an issuer principal, proof algorithm and seed hash.
90pub fn issuer_proof_binding_hash(
91    issuer_pid: Principal,
92    issuer_proof_alg: IssuerProofAlgorithm,
93    issuer_proof_binding: IssuerProofBinding,
94) -> Result<[u8; 32], CanonicalAuthError> {
95    hash_encoded(&[ISSUER_PROOF_BINDING_HASH_DOMAIN], false, &|out| {
96        encode_principal(out, issuer_pid)?;
97        encode_issuer_proof_algorithm(out, issuer_proof_alg);
98        encode_issuer_proof_binding(out, issuer_proof_binding);
99        Ok(())
100    })
101}
102
103/// Hash the exact validated role label under the existing role domain.
104pub fn role_hash(role: &AuthRole) -> Result<[u8; 32], CanonicalAuthError> {
105    hash_encoded(&[], false, &|out| {
106        out(DOMAIN_SEPARATOR);
107        out(&[CanonicalDomain::RoleHash as u8]);
108        encode_string(out, role.as_str())
109    })
110}
111
112/// Encode a certificate without changing grant order or normalizing labels.
113pub fn cert_bytes(cert: &DelegationCert) -> Result<Vec<u8>, CanonicalAuthError> {
114    let mut out = Vec::with_capacity(128);
115    encode_cert(&mut |bytes| out.extend_from_slice(bytes), cert)?;
116    Ok(out)
117}
118
119fn encode_cert(out: &mut Sink<'_>, cert: &DelegationCert) -> Result<(), CanonicalAuthError> {
120    out(DOMAIN_SEPARATOR);
121    out(&[CanonicalDomain::DelegationCert as u8]);
122
123    encode_principal(out, cert.root_pid)?;
124    encode_principal(out, cert.issuer_pid)?;
125    encode_issuer_proof_algorithm(out, cert.issuer_proof_alg);
126    encode_fixed_32(out, cert.issuer_proof_binding_hash);
127    encode_issuer_proof_binding(out, cert.issuer_proof_binding);
128    encode_u64(out, cert.issued_at_ns);
129    encode_u64(out, cert.not_before_ns);
130    encode_u64(out, cert.expires_at_ns);
131    encode_u64(out, cert.max_token_ttl_ns);
132    encode_audience(out, &cert.aud);
133    encode_role_grants(out, &cert.grants)?;
134
135    Ok(())
136}
137
138fn encode_issuer_proof_algorithm(out: &mut Sink<'_>, alg: IssuerProofAlgorithm) {
139    let tag = match alg {
140        IssuerProofAlgorithm::IcCanisterSignatureV1 => 1,
141    };
142    out(&[tag]);
143}
144
145fn encode_audience(out: &mut Sink<'_>, audience: &DelegationAudience) {
146    match audience {
147        DelegationAudience::Fleet(fleet) => {
148            out(&[1]);
149            encode_fleet_key(out, *fleet);
150        }
151    }
152}
153
154fn encode_fleet_key(out: &mut Sink<'_>, fleet: AudienceId) {
155    encode_fixed_32(out, *fleet.canonical_network_id.as_bytes());
156    encode_fixed_32(out, *fleet.fleet_id.as_bytes());
157}
158
159// Same-call structural evidence borrows the exact immutable grants it checked.
160// It never authenticates their source or admits authority.
161pub(crate) struct CheckedGrants<'a>(&'a [DelegatedRoleGrant]);
162impl<'a> CheckedGrants<'a> {
163    pub(crate) fn bounded(
164        grants: &'a [DelegatedRoleGrant],
165        max_grants: usize,
166        max_scopes: usize,
167    ) -> Result<Self, crate::certificate_issuance::GrantValidationError> {
168        crate::certificate_issuance::validate_grants(grants, max_grants, max_scopes)?;
169        Ok(Self(grants))
170    }
171
172    pub(crate) fn encode(&self, out: &mut Sink<'_>) -> Result<(), CanonicalAuthError> {
173        encode_len(out, self.0.len())?;
174        for grant in self.0 {
175            encode_grant(out, grant)?;
176        }
177        Ok(())
178    }
179}
180
181fn encode_role_grants(
182    out: &mut Sink<'_>,
183    grants: &[DelegatedRoleGrant],
184) -> Result<(), CanonicalAuthError> {
185    encode_len(out, grants.len())?;
186    let mut previous = None;
187    for grant in grants {
188        let current = grant.target.as_str().as_bytes();
189        if previous.is_some_and(|previous| previous >= current) {
190            return Err(CanonicalAuthError::NonCanonicalRoles);
191        }
192        previous = Some(current);
193        validate_scopes(&grant.scopes)?;
194        encode_grant(out, grant)?;
195    }
196    Ok(())
197}
198
199fn encode_grant(out: &mut Sink<'_>, grant: &DelegatedRoleGrant) -> Result<(), CanonicalAuthError> {
200    encode_role(out, &grant.target)?;
201    encode_len(out, grant.scopes.len())?;
202    for scope in &grant.scopes {
203        encode_bytes(out, scope.as_str().as_bytes())?;
204    }
205    Ok(())
206}
207
208fn hash_encoded(
209    prefix: &[&[u8]],
210    length_prefixed: bool,
211    encode: &dyn Fn(&mut Sink<'_>) -> Result<(), CanonicalAuthError>,
212) -> Result<[u8; 32], CanonicalAuthError> {
213    let mut hash = Sha256::new();
214    for bytes in prefix {
215        hash.update(bytes);
216    }
217    if length_prefixed {
218        let mut length = 0u64;
219        encode(&mut |bytes| length = length.saturating_add(bytes.len() as u64))?;
220        let length = u32::try_from(length).map_err(|_| CanonicalAuthError::LengthOverflow)?;
221        hash.update(length.to_be_bytes());
222    }
223    encode(&mut |bytes| hash.update(bytes))?;
224    Ok(hash.finalize().into())
225}
226
227fn encode_chain_key_batch_header(
228    out: &mut Sink<'_>,
229    header: &ChainKeyBatchHeaderV1,
230) -> Result<(), CanonicalAuthError> {
231    encode_u16(out, header.schema_version);
232    encode_principal(out, header.root_canister_id)?;
233    encode_fixed_32(out, header.batch_id);
234    encode_u64(out, header.proof_epoch);
235    encode_u64(out, header.registry_epoch);
236    encode_fixed_32(out, header.registry_hash);
237    encode_fixed_32(out, header.tree_root);
238    encode_u64(out, header.not_before_ns);
239    encode_u64(out, header.expires_at_ns);
240    encode_chain_key_algorithm(out, header.algorithm);
241    encode_chain_key_key_id(out, &header.key_id)?;
242    encode_fixed_32(out, header.derivation_path_hash);
243    encode_u64(out, header.key_version);
244    Ok(())
245}
246
247fn encode_chain_key_delegation_cert(
248    out: &mut Sink<'_>,
249    cert: &ChainKeyDelegationCertV1,
250) -> Result<(), CanonicalAuthError> {
251    encode_principal(out, cert.root_canister_id)?;
252    encode_principal(out, cert.issuer_canister_id)?;
253    encode_u64(out, cert.proof_epoch);
254    encode_issuer_proof_algorithm(out, cert.issuer_proof_algorithm);
255    encode_fixed_32(out, cert.issuer_proof_binding_hash);
256    encode_issuer_proof_binding(out, cert.issuer_proof_binding);
257    encode_u64(out, cert.max_token_ttl_ns);
258    encode_audience(out, &cert.audience);
259    encode_role_grants(out, &cert.grants)?;
260    encode_u64(out, cert.not_before_ns);
261    encode_u64(out, cert.expires_at_ns);
262    encode_u64(out, cert.registry_epoch);
263    encode_fixed_32(out, cert.registry_hash);
264    Ok(())
265}
266
267fn encode_root_proof(out: &mut Sink<'_>, proof: &RootProof) -> Result<(), CanonicalAuthError> {
268    match proof {
269        RootProof::IcChainKeyBatchSignatureV1(proof) => {
270            out(&[2]);
271            encode_chain_key_proof(out, proof)?;
272        }
273    }
274    Ok(())
275}
276
277fn encode_chain_key_proof(
278    out: &mut Sink<'_>,
279    proof: &IcChainKeyBatchSignatureProofV1,
280) -> Result<(), CanonicalAuthError> {
281    encode_chain_key_batch_header(out, &proof.header)?;
282    encode_chain_key_delegation_cert(out, &proof.delegation_cert)?;
283    encode_chain_key_witness(out, &proof.issuer_witness)?;
284    encode_chain_key_signature(out, &proof.signature)?;
285    Ok(())
286}
287
288fn encode_chain_key_witness(
289    out: &mut Sink<'_>,
290    witness: &ChainKeyBatchWitnessV1,
291) -> Result<(), CanonicalAuthError> {
292    encode_len(out, witness.steps.len())?;
293    for step in &witness.steps {
294        match step {
295            ChainKeyBatchWitnessStepV1::LeftSibling(hash) => {
296                out(&[1]);
297                encode_fixed_32(out, *hash);
298            }
299            ChainKeyBatchWitnessStepV1::RightSibling(hash) => {
300                out(&[2]);
301                encode_fixed_32(out, *hash);
302            }
303        }
304    }
305    Ok(())
306}
307
308fn encode_chain_key_signature(
309    out: &mut Sink<'_>,
310    signature: &ChainKeyRootSignatureV1,
311) -> Result<(), CanonicalAuthError> {
312    encode_chain_key_algorithm(out, signature.algorithm);
313    encode_chain_key_key_id(out, &signature.key_id)?;
314    encode_chain_key_derivation_path(out, &signature.derivation_path)?;
315    encode_bytes(out, &signature.public_key)?;
316    encode_bytes(out, &signature.signature)?;
317    Ok(())
318}
319
320fn encode_chain_key_derivation_path(
321    out: &mut Sink<'_>,
322    derivation_path: &[Vec<u8>],
323) -> Result<(), CanonicalAuthError> {
324    encode_len(out, derivation_path.len())?;
325    for path_component in derivation_path {
326        encode_bytes(out, path_component)?;
327    }
328    Ok(())
329}
330
331fn encode_chain_key_algorithm(out: &mut Sink<'_>, algorithm: ChainKeyAlgorithm) {
332    let tag = match algorithm {
333        ChainKeyAlgorithm::EcdsaSecp256k1 => 1,
334    };
335    out(&[tag]);
336}
337
338fn encode_chain_key_key_id(
339    out: &mut Sink<'_>,
340    key_id: &ChainKeyKeyId,
341) -> Result<(), CanonicalAuthError> {
342    encode_string(out, &key_id.name)?;
343    Ok(())
344}
345
346fn encode_issuer_proof_binding(out: &mut Sink<'_>, binding: IssuerProofBinding) {
347    match binding {
348        IssuerProofBinding::IcCanisterSignatureV1 { seed_hash } => {
349            out(&[1]);
350            encode_fixed_32(out, seed_hash);
351        }
352    }
353}
354
355fn encode_role(out: &mut Sink<'_>, role: &AuthRole) -> Result<(), CanonicalAuthError> {
356    encode_bytes(out, role.as_str().as_bytes())?;
357    Ok(())
358}
359
360/// Validate strictly increasing, unique UTF-8 byte order of checked labels.
361///
362/// An empty list is valid. Cardinality, normalization and application authority
363/// remain caller-owned; use the bounded grant validator for nonempty grants.
364pub fn validate_scopes(scopes: &[ScopeLabel]) -> Result<(), CanonicalAuthError> {
365    let mut previous = None;
366    for scope in scopes {
367        let current = scope.as_str().as_bytes();
368        if previous.is_some_and(|previous| previous >= current) {
369            return Err(CanonicalAuthError::NonCanonicalScopes);
370        }
371        previous = Some(current);
372    }
373
374    Ok(())
375}
376
377/// Check the existing lowercase, colon-separated application-scope grammar.
378pub fn validate_scope_label(scope: &str) -> Result<(), CanonicalAuthError> {
379    ScopeLabel::validate(scope).map_err(Into::into)
380}
381
382fn encode_string(out: &mut Sink<'_>, value: &str) -> Result<(), CanonicalAuthError> {
383    encode_bytes(out, value.as_bytes())?;
384    Ok(())
385}
386
387pub(crate) fn encode_principal(
388    out: &mut Sink<'_>,
389    principal: Principal,
390) -> Result<(), CanonicalAuthError> {
391    encode_bytes(out, principal.as_slice())?;
392    Ok(())
393}
394
395fn encode_bytes(out: &mut Sink<'_>, bytes: &[u8]) -> Result<(), CanonicalAuthError> {
396    encode_len(out, bytes.len())?;
397    out(bytes);
398    Ok(())
399}
400
401fn encode_fixed_32(out: &mut Sink<'_>, bytes: [u8; 32]) {
402    out(&bytes);
403}
404
405fn encode_u64(out: &mut Sink<'_>, value: u64) {
406    out(&value.to_be_bytes());
407}
408
409fn encode_u16(out: &mut Sink<'_>, value: u16) {
410    out(&value.to_be_bytes());
411}
412
413fn encode_len(out: &mut Sink<'_>, len: usize) -> Result<(), CanonicalAuthError> {
414    let len = u32::try_from(len).map_err(|_| CanonicalAuthError::LengthOverflow)?;
415    out(&len.to_be_bytes());
416    Ok(())
417}
418
419#[cfg(test)]
420mod tests;