Skip to main content

ic_auth/certificate_issuance/
mod.rs

1//! Pure certificate issuance rules, without signing, time or authority admission.
2//!
3//! The host supplies the expected Root and bounds from protected configuration.
4//! Success checks shape and binding bytes only; it does not authenticate a
5//! certificate, authorize issuance or install a delegation. No field is normalized.
6
7use crate::canonical::{CanonicalAuthError, issuer_proof_binding_hash, validate_scopes};
8use ic_auth_protocol_types::{AuthRole, DelegatedRoleGrant, DelegationCert, Principal, ScopeLabel};
9use thiserror::Error;
10
11/// Explicit host-selected issuance bounds; no Fleet or grant defaults are inferred.
12#[derive(Clone, Copy, Debug, Eq, PartialEq)]
13pub struct CertificateIssuanceLimits {
14    /// Maximum positive certificate validity duration in nanoseconds.
15    pub max_cert_ttl_ns: u64,
16    /// Maximum credential lifetime the certificate may delegate, in nanoseconds.
17    pub max_token_ttl_ns: u64,
18    /// Maximum nonempty role grants accepted by this host.
19    pub max_grants: usize,
20    /// Maximum nonempty scopes per role grant accepted by this host.
21    pub max_scopes_per_grant: usize,
22}
23
24/// Ordered shape rejection, separate from cryptographic and current-clock checks.
25/// Role grammar is already enforced by the passive `AuthRole` type at decoding
26/// or construction; scope syntax and exact grant ordering are checked here.
27#[derive(Debug, Eq, Error, PartialEq)]
28pub enum CertificateIssuanceError {
29    #[error("certificate Root mismatch (expected {expected}, found {found})")]
30    /// Certificate names a different root than protected host configuration.
31    RootPidMismatch {
32        /// Root identity supplied by trusted host configuration.
33        expected: Principal,
34        /// Root identity carried in the submitted certificate.
35        found: Principal,
36    },
37    #[error(transparent)]
38    /// Certificate validity or delegated token lifetime violates host bounds.
39    Lifetime(#[from] CertificateLifetimeError),
40    #[error(transparent)]
41    /// Grants violate the canonical shape or host cardinality bounds.
42    Grants(#[from] GrantValidationError),
43    #[error("issuer proof binding hash mismatch")]
44    /// Submitted binding hash does not match the canonical issuer binding.
45    IssuerProofBindingHashMismatch,
46    #[error(transparent)]
47    /// Certificate material cannot be encoded under the canonical contract.
48    Canonical(#[from] CanonicalAuthError),
49}
50
51/// Validate Root binding, lifetime, canonical bounded grants, then issuer binding.
52/// Exact bound equality is accepted. Anonymous principals are not implicitly
53/// refused: identity eligibility, live policy, proof verification and clock
54/// acceptance remain separate host/verification obligations.
55pub 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/// Ordered lifetime causes shared by issuance and delegation verification.
75/// Neither this error nor the shape validator establishes current authority.
76#[derive(Debug, Eq, Error, PartialEq)]
77pub enum CertificateLifetimeError {
78    #[error("certificate was issued after its validity start")]
79    /// Issue-time metadata is later than the certificate validity start.
80    IssuedAfterStart,
81    #[error("certificate validity must have positive duration")]
82    /// Expiry is not strictly later than validity start.
83    InvalidWindow,
84    #[error("certificate TTL {ttl_ns} exceeds host maximum {max_ttl_ns}")]
85    /// Certificate validity exceeds the configured duration ceiling.
86    CertTtlExceeded {
87        /// Submitted certificate duration in nanoseconds.
88        ttl_ns: u64,
89        /// Host-admitted duration ceiling in nanoseconds.
90        max_ttl_ns: u64,
91    },
92    #[error("delegated token TTL must be greater than zero")]
93    /// Delegation permits a zero token lifetime, which is not a valid policy.
94    TokenTtlZero,
95    #[error("delegated token TTL {ttl_ns} exceeds host maximum {max_ttl_ns}")]
96    /// Delegated token lifetime exceeds the host's maximum.
97    TokenTtlExceeded {
98        /// Delegated token lifetime in nanoseconds.
99        ttl_ns: u64,
100        /// Host-admitted token lifetime ceiling in nanoseconds.
101        max_ttl_ns: u64,
102    },
103    #[error("delegated token TTL {token_ttl_ns} exceeds certificate duration {cert_ttl_ns}")]
104    /// Delegated token lifetime is longer than the certificate's entire window.
105    TokenTtlOutlivesCert {
106        /// Delegated token lifetime in nanoseconds.
107        token_ttl_ns: u64,
108        /// Certificate validity duration in nanoseconds.
109        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/// A standalone grant-shape failure, before any certificate or token exists.
153#[derive(Debug, Eq, Error, PartialEq)]
154pub enum GrantValidationError {
155    #[error("grants are empty")]
156    /// No role grants were supplied.
157    Empty,
158    #[error("{found} grants exceed maximum {max}")]
159    /// The grant list exceeds the configured role count.
160    TooMany {
161        /// Number of submitted grants.
162        found: usize,
163        /// Inclusive host grant-count ceiling.
164        max: usize,
165    },
166    #[error("grant for {role:?} has no scopes")]
167    /// A role grant contains no scopes.
168    EmptyScopes {
169        /// Role with the empty scope list.
170        role: AuthRole,
171    },
172    #[error("grant for {role:?} has {found} scopes; maximum is {max}")]
173    /// One role's scope list exceeds the configured count.
174    TooManyScopes {
175        /// Role whose scope list exceeds the bound.
176        role: AuthRole,
177        /// Submitted scope count for that role.
178        found: usize,
179        /// Inclusive per-role scope ceiling.
180        max: usize,
181    },
182    #[error(transparent)]
183    /// Role or scope ordering/encoding is noncanonical; inputs are never sorted here.
184    Canonical(CanonicalAuthError),
185}
186
187/// Validate nonempty grants against caller-owned cardinality bounds.
188///
189/// Checks the grant count first, then each role's strict byte ordering, scope
190/// count and strict scope ordering in input order. It neither sorts nor grants
191/// authority. Roles and scope labels are checked by their types; hosts retain
192/// raw projection and its error precedence at their own input boundary.
193pub 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
232// Both callers admit canonical parent scopes first: protected claims authority
233// through validate_grants, or the delegation certificate through cert_hash.
234pub(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
251// The ceiling must already be canonical. Requested scopes need not be ordered
252// (ordinary authorization accepts host-required scopes in any order).
253pub(crate) fn scopes_are_subset(requested: &[ScopeLabel], ceiling: &[ScopeLabel]) -> bool {
254    requested.iter().all(|scope| {
255        let scope = scope.as_str();
256        // The measured one/two-scope profile is cheaper with a direct scan;
257        // wider canonical ceilings avoid repeated full scans through search.
258        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;