Skip to main content

ic_auth/portable/
rules.rs

1//! Common portable claims checks; neither proof verification nor session admission.
2
3use super::{PortableEncodingError, ValidatedGrants, browser_principal, validate_shape};
4use crate::certificate_issuance::{grants_are_subset, positive_duration};
5use ic_auth_protocol_types::{AudienceId, PortableClaims, PortableMechanism, Principal};
6use thiserror::Error;
7
8/// Protected runtime and active enrollment inputs, never inferred from claims.
9/// The host must select current, unrevoked authority under its transaction lock.
10/// Generation, login revocation, replay and atomic session writes remain host/
11/// session-engine obligations; this context cannot attest its own provenance.
12#[derive(Clone, Copy, Debug)]
13pub struct PortableAuthority<'a> {
14    /// Protected intended audience, obtained independently of the credential.
15    pub audience: &'a AudienceId,
16    /// Issuer selected by current protected enrollment.
17    pub issuer: Principal,
18    /// Proof mechanism authorized by that enrollment.
19    pub mechanism: PortableMechanism,
20    /// Exact enrolled issuer key binding, compared with signed claims.
21    pub key_binding_id: [u8; 32],
22    /// Immutable checked grant shape from the current protected enrollment.
23    pub grants: &'a ValidatedGrants,
24    /// Actual authenticated ingress sender, not an account subject or request field.
25    pub caller: Principal,
26    /// Authenticated host clock in nanoseconds.
27    pub now_ns: u64,
28    /// Inclusive start of the current issuer authority window.
29    pub authority_not_before_ns: u64,
30    /// Exclusive issuer authority deadline in nanoseconds.
31    pub authority_expires_at_ns: u64,
32    /// Exclusive host enrollment deadline, independently bounding the session.
33    pub enrollment_expires_at_ns: u64,
34    /// Protected policy floor; a local timestamp alone cannot fence lost state.
35    pub min_login_started_at_ns: u64,
36}
37
38/// Current authority plus fresh-proof admission constraints. Ordinary session
39/// authorization uses `PortableAuthority` without proof TTL or issuance inputs.
40#[derive(Clone, Copy, Debug)]
41pub struct PortableClaimsContext<'a> {
42    /// Current protected enrollment, runtime caller and clock.
43    pub authority: PortableAuthority<'a>,
44    /// Protected issuance floor; timestamps alone do not recover lost revocation state.
45    pub min_proof_issued_at_ns: u64,
46    /// Positive host limits, capped at 90 days and 60 seconds respectively.
47    pub max_login_ttl_ns: u64,
48    /// Maximum admission-proof lifetime in nanoseconds, capped at 60 seconds.
49    pub max_proof_ttl_ns: u64,
50}
51
52impl PortableAuthority<'_> {
53    // Shared structural authority policy, independent of clock, proof lifetime,
54    // caller and session liveness. Each path preserves its own refusal type.
55    pub(crate) fn authority_shape_valid(&self) -> bool {
56        self.issuer != Principal::anonymous()
57            && self.authority_not_before_ns < self.authority_expires_at_ns
58    }
59}
60
61/// Pure rejection of claims against protected context; success is not admission.
62#[derive(Debug, Error, Eq, PartialEq)]
63pub enum PortableClaimsError {
64    #[error("invalid protected portable claims context")]
65    /// Protected authority or configured time bounds are internally invalid.
66    InvalidContext,
67    #[error("portable audience does not match protected authority")]
68    /// Signed audience differs from the protected receiver audience.
69    AudienceMismatch,
70    #[error("portable issuer does not match protected authority")]
71    /// Signed issuer differs from the enrolled issuer.
72    IssuerMismatch,
73    #[error("portable mechanism does not match protected authority")]
74    /// Signed proof mechanism differs from the enrolled mechanism.
75    MechanismMismatch,
76    #[error("portable key binding does not match protected authority")]
77    /// Signed key binding differs from the enrolled binding.
78    KeyMismatch,
79    #[error("browser key does not identify the authenticated caller")]
80    /// The browser key does not identify the authenticated ingress caller.
81    CallerMismatch,
82    #[error("portable grants exceed protected authority")]
83    /// Credential grants exceed current protected issuer authority.
84    GrantsExceeded,
85    #[error("portable login or proof window is invalid")]
86    /// Login or proof time windows are inconsistent or exceed host bounds.
87    InvalidWindow,
88    #[error("portable proof is not yet valid")]
89    /// The proof starts after the current host time; authenticity is not implied.
90    NotYetValid,
91    #[error("portable proof has expired")]
92    /// The proof admission window has ended.
93    Expired,
94    #[error("portable login or issuance predates the protected reset floor")]
95    /// Login start or issuance precedes a protected acceptance floor.
96    BeforeReset,
97    #[error("portable authority or enrollment is not current")]
98    /// Issuer authority or enrollment is outside its live window.
99    StaleAuthority,
100    #[error(transparent)]
101    /// Claims fail canonical structural admission.
102    Encoding(#[from] PortableEncodingError),
103}
104
105/// Check both mechanisms' caller, protected bindings, grants and exact time bounds.
106///
107/// Success authenticates nothing by itself. Refusal may precede cryptography;
108/// notably `NotYetValid` is a bounded retry hint, never evidence of a valid proof.
109/// No skew grace is added. The host must preserve revocation/replay state and
110/// fail closed after state loss; these timestamp checks cannot replace it.
111pub fn validate_claims_context(
112    claims: &PortableClaims,
113    context: &PortableClaimsContext<'_>,
114) -> Result<(), PortableClaimsError> {
115    validate_context(context)?;
116    validate_shape(claims)?;
117    validate_bindings(
118        claims,
119        browser_principal(&claims.browser_public_key),
120        context,
121    )
122}
123
124// DecodedPortableClaims alone may skip shape admission: its owned claims have
125// passed the canonical decoder and cannot be edited by callers.
126#[cfg(any(
127    feature = "portable-signature-verification",
128    feature = "certified-proof-verification"
129))]
130pub(super) fn validate_decoded_context(
131    claims: &PortableClaims,
132    browser_caller: Principal,
133    context: &PortableClaimsContext<'_>,
134) -> Result<(), PortableClaimsError> {
135    validate_context(context)?;
136    validate_bindings(claims, browser_caller, context)
137}
138
139fn validate_context(context: &PortableClaimsContext<'_>) -> Result<(), PortableClaimsError> {
140    use PortableClaimsError as Error;
141    let authority = &context.authority;
142    if context.max_login_ttl_ns == 0
143        || context.max_login_ttl_ns > crate::limits::MAX_LOGIN_NS
144        || context.max_proof_ttl_ns == 0
145        || context.max_proof_ttl_ns > crate::limits::MAX_PROOF_NS
146        || !authority.authority_shape_valid()
147        || authority.enrollment_expires_at_ns == 0
148    {
149        return Err(Error::InvalidContext);
150    }
151    Ok(())
152}
153
154fn validate_bindings(
155    claims: &PortableClaims,
156    browser_caller: Principal,
157    context: &PortableClaimsContext<'_>,
158) -> Result<(), PortableClaimsError> {
159    use PortableClaimsError as Error;
160    let authority = &context.authority;
161    if claims.audience != *authority.audience {
162        return Err(Error::AudienceMismatch);
163    }
164    if claims.issuer != authority.issuer {
165        return Err(Error::IssuerMismatch);
166    }
167    if claims.mechanism != authority.mechanism {
168        return Err(Error::MechanismMismatch);
169    }
170    if claims.key_binding_id != authority.key_binding_id {
171        return Err(Error::KeyMismatch);
172    }
173    if browser_caller != authority.caller {
174        return Err(Error::CallerMismatch);
175    }
176    if !grants_are_subset(&claims.grants, authority.grants.as_slice()) {
177        return Err(Error::GrantsExceeded);
178    }
179    if positive_duration(claims.login_started_at_ns, claims.login_deadline_ns)
180        .is_none_or(|ttl| ttl > context.max_login_ttl_ns)
181        || positive_duration(claims.issued_at_ns, claims.admission_expires_at_ns)
182            .is_none_or(|ttl| ttl > context.max_proof_ttl_ns)
183        || claims.login_started_at_ns > claims.issued_at_ns
184        || claims.admission_expires_at_ns > claims.login_deadline_ns
185    {
186        return Err(Error::InvalidWindow);
187    }
188    if claims.login_started_at_ns < authority.min_login_started_at_ns
189        || claims.issued_at_ns < context.min_proof_issued_at_ns
190    {
191        return Err(Error::BeforeReset);
192    }
193    if authority.now_ns < authority.authority_not_before_ns
194        || authority.now_ns >= authority.authority_expires_at_ns
195        || authority.now_ns >= authority.enrollment_expires_at_ns
196        || claims.issued_at_ns < authority.authority_not_before_ns
197    {
198        return Err(Error::StaleAuthority);
199    }
200    if authority.now_ns < claims.issued_at_ns {
201        return Err(Error::NotYetValid);
202    }
203    if authority.now_ns >= claims.admission_expires_at_ns {
204        return Err(Error::Expired);
205    }
206    Ok(())
207}