ic_auth/certificate_issuance/
mod.rs1use crate::canonical::{CanonicalAuthError, issuer_proof_binding_hash, validate_scopes};
8use ic_auth_protocol_types::{AuthRole, DelegatedRoleGrant, DelegationCert, Principal, ScopeLabel};
9use thiserror::Error;
10
11#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub struct CertificateIssuanceLimits {
14 pub max_cert_ttl_ns: u64,
16 pub max_token_ttl_ns: u64,
18 pub max_grants: usize,
20 pub max_scopes_per_grant: usize,
22}
23
24#[derive(Debug, Eq, Error, PartialEq)]
28pub enum CertificateIssuanceError {
29 #[error("certificate Root mismatch (expected {expected}, found {found})")]
30 RootPidMismatch {
32 expected: Principal,
34 found: Principal,
36 },
37 #[error(transparent)]
38 Lifetime(#[from] CertificateLifetimeError),
40 #[error(transparent)]
41 Grants(#[from] GrantValidationError),
43 #[error("issuer proof binding hash mismatch")]
44 IssuerProofBindingHashMismatch,
46 #[error(transparent)]
47 Canonical(#[from] CanonicalAuthError),
49}
50
51pub fn validate_certificate_issuance(
56 cert: &DelegationCert,
57 expected_root: Principal,
58 limits: CertificateIssuanceLimits,
59) -> Result<(), CertificateIssuanceError> {
60 if cert.root_pid != expected_root {
61 return Err(CertificateIssuanceError::RootPidMismatch {
62 expected: expected_root,
63 found: cert.root_pid,
64 });
65 }
66 validate_certificate_lifetime(cert, limits.max_cert_ttl_ns, limits.max_token_ttl_ns)?;
67 validate_grants(&cert.grants, limits.max_grants, limits.max_scopes_per_grant)?;
68 if !issuer_binding_matches(cert)? {
69 return Err(CertificateIssuanceError::IssuerProofBindingHashMismatch);
70 }
71 Ok(())
72}
73
74#[derive(Debug, Eq, Error, PartialEq)]
77pub enum CertificateLifetimeError {
78 #[error("certificate was issued after its validity start")]
79 IssuedAfterStart,
81 #[error("certificate validity must have positive duration")]
82 InvalidWindow,
84 #[error("certificate TTL {ttl_ns} exceeds host maximum {max_ttl_ns}")]
85 CertTtlExceeded {
87 ttl_ns: u64,
89 max_ttl_ns: u64,
91 },
92 #[error("delegated token TTL must be greater than zero")]
93 TokenTtlZero,
95 #[error("delegated token TTL {ttl_ns} exceeds host maximum {max_ttl_ns}")]
96 TokenTtlExceeded {
98 ttl_ns: u64,
100 max_ttl_ns: u64,
102 },
103 #[error("delegated token TTL {token_ttl_ns} exceeds certificate duration {cert_ttl_ns}")]
104 TokenTtlOutlivesCert {
106 token_ttl_ns: u64,
108 cert_ttl_ns: u64,
110 },
111}
112
113pub(crate) fn positive_duration(start: u64, end: u64) -> Option<u64> {
114 end.checked_sub(start).filter(|duration| *duration != 0)
115}
116
117pub(crate) fn validate_certificate_lifetime(
118 cert: &DelegationCert,
119 max_cert_ttl_ns: u64,
120 max_token_ttl_ns: u64,
121) -> Result<(), CertificateLifetimeError> {
122 use CertificateLifetimeError as E;
123 if cert.issued_at_ns > cert.not_before_ns {
124 return Err(E::IssuedAfterStart);
125 }
126 let cert_ttl_ns =
127 positive_duration(cert.not_before_ns, cert.expires_at_ns).ok_or(E::InvalidWindow)?;
128 if cert_ttl_ns > max_cert_ttl_ns {
129 return Err(E::CertTtlExceeded {
130 ttl_ns: cert_ttl_ns,
131 max_ttl_ns: max_cert_ttl_ns,
132 });
133 }
134 if cert.max_token_ttl_ns == 0 {
135 return Err(E::TokenTtlZero);
136 }
137 if cert.max_token_ttl_ns > max_token_ttl_ns {
138 return Err(E::TokenTtlExceeded {
139 ttl_ns: cert.max_token_ttl_ns,
140 max_ttl_ns: max_token_ttl_ns,
141 });
142 }
143 if cert.max_token_ttl_ns > cert_ttl_ns {
144 return Err(E::TokenTtlOutlivesCert {
145 token_ttl_ns: cert.max_token_ttl_ns,
146 cert_ttl_ns,
147 });
148 }
149 Ok(())
150}
151
152#[derive(Debug, Eq, Error, PartialEq)]
154pub enum GrantValidationError {
155 #[error("grants are empty")]
156 Empty,
158 #[error("{found} grants exceed maximum {max}")]
159 TooMany {
161 found: usize,
163 max: usize,
165 },
166 #[error("grant for {role:?} has no scopes")]
167 EmptyScopes {
169 role: AuthRole,
171 },
172 #[error("grant for {role:?} has {found} scopes; maximum is {max}")]
173 TooManyScopes {
175 role: AuthRole,
177 found: usize,
179 max: usize,
181 },
182 #[error(transparent)]
183 Canonical(CanonicalAuthError),
185}
186
187pub fn validate_grants(
194 grants: &[DelegatedRoleGrant],
195 max_grants: usize,
196 max_scopes_per_grant: usize,
197) -> Result<(), GrantValidationError> {
198 use GrantValidationError as E;
199 if grants.is_empty() {
200 return Err(E::Empty);
201 }
202 if grants.len() > max_grants {
203 return Err(E::TooMany {
204 found: grants.len(),
205 max: max_grants,
206 });
207 }
208 let mut previous = None;
209 for grant in grants {
210 let role = grant.target.as_str().as_bytes();
211 if previous.is_some_and(|previous| previous >= role) {
212 return Err(E::Canonical(CanonicalAuthError::NonCanonicalRoles));
213 }
214 previous = Some(role);
215 if grant.scopes.is_empty() {
216 return Err(E::EmptyScopes {
217 role: grant.target.clone(),
218 });
219 }
220 if grant.scopes.len() > max_scopes_per_grant {
221 return Err(E::TooManyScopes {
222 role: grant.target.clone(),
223 found: grant.scopes.len(),
224 max: max_scopes_per_grant,
225 });
226 }
227 validate_scopes(&grant.scopes).map_err(E::Canonical)?;
228 }
229 Ok(())
230}
231
232pub(crate) fn grants_are_subset(
235 grants: &[DelegatedRoleGrant],
236 ceiling: &[DelegatedRoleGrant],
237) -> bool {
238 grants.iter().all(|child| {
239 grant_for_role(ceiling, &child.target)
240 .is_some_and(|parent| scopes_are_subset(&child.scopes, &parent.scopes))
241 })
242}
243
244pub(crate) fn grant_for_role<'a>(
245 grants: &'a [DelegatedRoleGrant],
246 role: &AuthRole,
247) -> Option<&'a DelegatedRoleGrant> {
248 grants.iter().find(|grant| &grant.target == role)
249}
250
251pub(crate) fn scopes_are_subset(requested: &[ScopeLabel], ceiling: &[ScopeLabel]) -> bool {
254 requested.iter().all(|scope| {
255 let scope = scope.as_str();
256 if ceiling.len() <= 2 {
259 ceiling.iter().any(|allowed| allowed.as_str() == scope)
260 } else {
261 ceiling
262 .binary_search_by(|allowed| allowed.as_str().cmp(scope))
263 .is_ok()
264 }
265 })
266}
267
268pub(crate) fn issuer_binding_matches(cert: &DelegationCert) -> Result<bool, CanonicalAuthError> {
269 Ok(issuer_proof_binding_hash(
270 cert.issuer_pid,
271 cert.issuer_proof_alg,
272 cert.issuer_proof_binding,
273 )? == cert.issuer_proof_binding_hash)
274}
275
276#[cfg(test)]
277mod tests;