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