1use ic_auth_protocol_types::*;
6use sha2::{Digest, Sha256};
7use thiserror::Error;
8
9pub(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#[repr(u8)]
21#[derive(Clone, Copy, Debug, Eq, PartialEq)]
22enum CanonicalDomain {
23 DelegationCert = 1,
24 DelegationProof = 3,
25 RoleHash = 4,
26}
27
28#[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
46pub fn cert_hash(cert: &DelegationCert) -> Result<[u8; 32], CanonicalAuthError> {
48 hash_encoded(&[], false, &|out| encode_cert(out, cert))
49}
50
51pub 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
61pub 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
70pub 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
79pub 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
89pub 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
103pub 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
112pub 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::<false>(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
159pub(crate) fn encode_role_grants<const ADMITTED: bool>(
162 out: &mut Sink<'_>,
163 grants: &[DelegatedRoleGrant],
164) -> Result<(), CanonicalAuthError> {
165 encode_len(out, grants.len())?;
166 let mut previous = None;
167 for grant in grants {
168 let current = grant.target.as_str().as_bytes();
169 if !ADMITTED && previous.is_some_and(|previous| previous >= current) {
170 return Err(CanonicalAuthError::NonCanonicalRoles);
171 }
172 previous = Some(current);
173 encode_role(out, &grant.target)?;
174 if !ADMITTED {
175 validate_scopes(&grant.scopes)?;
176 }
177 encode_len(out, grant.scopes.len())?;
178 for scope in &grant.scopes {
179 encode_bytes(out, scope.as_str().as_bytes())?;
180 }
181 }
182 Ok(())
183}
184
185fn hash_encoded(
186 prefix: &[&[u8]],
187 length_prefixed: bool,
188 encode: &dyn Fn(&mut Sink<'_>) -> Result<(), CanonicalAuthError>,
189) -> Result<[u8; 32], CanonicalAuthError> {
190 let mut hash = Sha256::new();
191 for bytes in prefix {
192 hash.update(bytes);
193 }
194 if length_prefixed {
195 let mut length = 0u64;
196 encode(&mut |bytes| length = length.saturating_add(bytes.len() as u64))?;
197 let length = u32::try_from(length).map_err(|_| CanonicalAuthError::LengthOverflow)?;
198 hash.update(length.to_be_bytes());
199 }
200 encode(&mut |bytes| hash.update(bytes))?;
201 Ok(hash.finalize().into())
202}
203
204fn encode_chain_key_batch_header(
205 out: &mut Sink<'_>,
206 header: &ChainKeyBatchHeaderV1,
207) -> Result<(), CanonicalAuthError> {
208 encode_u16(out, header.schema_version);
209 encode_principal(out, header.root_canister_id)?;
210 encode_fixed_32(out, header.batch_id);
211 encode_u64(out, header.proof_epoch);
212 encode_u64(out, header.registry_epoch);
213 encode_fixed_32(out, header.registry_hash);
214 encode_fixed_32(out, header.tree_root);
215 encode_u64(out, header.not_before_ns);
216 encode_u64(out, header.expires_at_ns);
217 encode_chain_key_algorithm(out, header.algorithm);
218 encode_chain_key_key_id(out, &header.key_id)?;
219 encode_fixed_32(out, header.derivation_path_hash);
220 encode_u64(out, header.key_version);
221 Ok(())
222}
223
224fn encode_chain_key_delegation_cert(
225 out: &mut Sink<'_>,
226 cert: &ChainKeyDelegationCertV1,
227) -> Result<(), CanonicalAuthError> {
228 encode_principal(out, cert.root_canister_id)?;
229 encode_principal(out, cert.issuer_canister_id)?;
230 encode_u64(out, cert.proof_epoch);
231 encode_issuer_proof_algorithm(out, cert.issuer_proof_algorithm);
232 encode_fixed_32(out, cert.issuer_proof_binding_hash);
233 encode_issuer_proof_binding(out, cert.issuer_proof_binding);
234 encode_u64(out, cert.max_token_ttl_ns);
235 encode_audience(out, &cert.audience);
236 encode_role_grants::<false>(out, &cert.grants)?;
237 encode_u64(out, cert.not_before_ns);
238 encode_u64(out, cert.expires_at_ns);
239 encode_u64(out, cert.registry_epoch);
240 encode_fixed_32(out, cert.registry_hash);
241 Ok(())
242}
243
244fn encode_root_proof(out: &mut Sink<'_>, proof: &RootProof) -> Result<(), CanonicalAuthError> {
245 match proof {
246 RootProof::IcChainKeyBatchSignatureV1(proof) => {
247 out(&[2]);
248 encode_chain_key_proof(out, proof)?;
249 }
250 }
251 Ok(())
252}
253
254fn encode_chain_key_proof(
255 out: &mut Sink<'_>,
256 proof: &IcChainKeyBatchSignatureProofV1,
257) -> Result<(), CanonicalAuthError> {
258 encode_chain_key_batch_header(out, &proof.header)?;
259 encode_chain_key_delegation_cert(out, &proof.delegation_cert)?;
260 encode_chain_key_witness(out, &proof.issuer_witness)?;
261 encode_chain_key_signature(out, &proof.signature)?;
262 Ok(())
263}
264
265fn encode_chain_key_witness(
266 out: &mut Sink<'_>,
267 witness: &ChainKeyBatchWitnessV1,
268) -> Result<(), CanonicalAuthError> {
269 encode_len(out, witness.steps.len())?;
270 for step in &witness.steps {
271 match step {
272 ChainKeyBatchWitnessStepV1::LeftSibling(hash) => {
273 out(&[1]);
274 encode_fixed_32(out, *hash);
275 }
276 ChainKeyBatchWitnessStepV1::RightSibling(hash) => {
277 out(&[2]);
278 encode_fixed_32(out, *hash);
279 }
280 }
281 }
282 Ok(())
283}
284
285fn encode_chain_key_signature(
286 out: &mut Sink<'_>,
287 signature: &ChainKeyRootSignatureV1,
288) -> Result<(), CanonicalAuthError> {
289 encode_chain_key_algorithm(out, signature.algorithm);
290 encode_chain_key_key_id(out, &signature.key_id)?;
291 encode_chain_key_derivation_path(out, &signature.derivation_path)?;
292 encode_bytes(out, &signature.public_key)?;
293 encode_bytes(out, &signature.signature)?;
294 Ok(())
295}
296
297fn encode_chain_key_derivation_path(
298 out: &mut Sink<'_>,
299 derivation_path: &[Vec<u8>],
300) -> Result<(), CanonicalAuthError> {
301 encode_len(out, derivation_path.len())?;
302 for path_component in derivation_path {
303 encode_bytes(out, path_component)?;
304 }
305 Ok(())
306}
307
308fn encode_chain_key_algorithm(out: &mut Sink<'_>, algorithm: ChainKeyAlgorithm) {
309 let tag = match algorithm {
310 ChainKeyAlgorithm::EcdsaSecp256k1 => 1,
311 };
312 out(&[tag]);
313}
314
315fn encode_chain_key_key_id(
316 out: &mut Sink<'_>,
317 key_id: &ChainKeyKeyId,
318) -> Result<(), CanonicalAuthError> {
319 encode_string(out, &key_id.name)?;
320 Ok(())
321}
322
323fn encode_issuer_proof_binding(out: &mut Sink<'_>, binding: IssuerProofBinding) {
324 match binding {
325 IssuerProofBinding::IcCanisterSignatureV1 { seed_hash } => {
326 out(&[1]);
327 encode_fixed_32(out, seed_hash);
328 }
329 }
330}
331
332fn encode_role(out: &mut Sink<'_>, role: &AuthRole) -> Result<(), CanonicalAuthError> {
333 encode_bytes(out, role.as_str().as_bytes())?;
334 Ok(())
335}
336
337pub fn validate_scopes(scopes: &[ScopeLabel]) -> Result<(), CanonicalAuthError> {
342 let mut previous = None;
343 for scope in scopes {
344 let current = scope.as_str().as_bytes();
345 if previous.is_some_and(|previous| previous >= current) {
346 return Err(CanonicalAuthError::NonCanonicalScopes);
347 }
348 previous = Some(current);
349 }
350
351 Ok(())
352}
353
354pub fn validate_scope_label(scope: &str) -> Result<(), CanonicalAuthError> {
356 ScopeLabel::validate(scope).map_err(Into::into)
357}
358
359fn encode_string(out: &mut Sink<'_>, value: &str) -> Result<(), CanonicalAuthError> {
360 encode_bytes(out, value.as_bytes())?;
361 Ok(())
362}
363
364pub(crate) fn encode_principal(
365 out: &mut Sink<'_>,
366 principal: Principal,
367) -> Result<(), CanonicalAuthError> {
368 encode_bytes(out, principal.as_slice())?;
369 Ok(())
370}
371
372fn encode_bytes(out: &mut Sink<'_>, bytes: &[u8]) -> Result<(), CanonicalAuthError> {
373 encode_len(out, bytes.len())?;
374 out(bytes);
375 Ok(())
376}
377
378fn encode_fixed_32(out: &mut Sink<'_>, bytes: [u8; 32]) {
379 out(&bytes);
380}
381
382fn encode_u64(out: &mut Sink<'_>, value: u64) {
383 out(&value.to_be_bytes());
384}
385
386fn encode_u16(out: &mut Sink<'_>, value: u16) {
387 out(&value.to_be_bytes());
388}
389
390fn encode_len(out: &mut Sink<'_>, len: usize) -> Result<(), CanonicalAuthError> {
391 let len = u32::try_from(len).map_err(|_| CanonicalAuthError::LengthOverflow)?;
392 out(&len.to_be_bytes());
393 Ok(())
394}
395
396#[cfg(test)]
397mod tests;