Skip to main content

ic_auth/portable/
mod.rs

1//! Canonical portable credential claims and explicit protected-context checks.
2//! Encoding, decoding and hashing alone do not verify time or authority.
3//! Context checks do not verify signatures, enrollment provenance or revocation.
4//! No value returned by this module is sufficient for session admission.
5
6#[cfg(any(
7    feature = "portable-signature-verification",
8    feature = "certified-proof-verification"
9))]
10mod decoded;
11mod grants;
12mod revocation;
13mod rules;
14mod verified;
15#[cfg(any(
16    feature = "portable-signature-verification",
17    feature = "certified-proof-verification"
18))]
19pub(crate) use decoded::{ContextualClaims, DecodedPortableClaims};
20pub use grants::ValidatedGrants;
21pub use revocation::{
22    LoginBinding, LoginRecordState, LoginRevocationChange, LoginRevocationError,
23    MemoryLoginRevocations,
24};
25pub use rules::{
26    PortableAuthority, PortableClaimsContext, PortableClaimsError, validate_claims_context,
27};
28pub use verified::VerifiedPortableClaims;
29
30use crate::canonical::{CanonicalAuthError, CheckedGrants, encode_principal};
31use crate::certificate_issuance::GrantValidationError;
32use crate::limits::{MAX_GRANTS, MAX_LABEL_BYTES, MAX_SCOPES_PER_GRANT};
33use ic_auth_protocol_types::{
34    AudienceId, CanonicalId, DelegatedRoleGrant, PortableClaims, PortableMechanism, Principal,
35};
36use sha2::{Digest, Sha256};
37use thiserror::Error;
38
39const DOMAIN: &[u8] = b"IC-AUTH-PORTABLE-CREDENTIAL\0";
40const SCHEMA: u16 = 2;
41
42/// Hard cap on the signed claims blob, independent of outer transport limits.
43pub use ic_auth_protocol_types::limits::MAX_CLAIMS_BYTES;
44
45/// Aggregate canonical grant-list budget for portable credentials, including
46/// counts, role labels and scope labels. Protected enrollment may be broader;
47/// issuers must select a bounded subset rather than truncate permissions.
48pub const MAX_CREDENTIAL_GRANT_BYTES: usize = 4096;
49
50/// Maximum role-scope entries across a portable credential. The same scope
51/// under two roles counts twice; protected enrollment may be broader.
52pub const MAX_CREDENTIAL_SCOPE_ENTRIES: usize = 32;
53
54// Every valid combination must fit, including all canonical length prefixes.
55// Keep this guarantee coupled to the actual role and label ceilings.
56const _: () = assert!(
57    4 + MAX_GRANTS * (8 + MAX_LABEL_BYTES) + MAX_CREDENTIAL_SCOPE_ENTRIES * (4 + MAX_LABEL_BYTES)
58        <= MAX_CREDENTIAL_GRANT_BYTES
59);
60
61/// Check grants for new portable issuance before reserving work or signing.
62/// At most 32 scope entries across 16 roles guarantees the canonical grant list
63/// fits the byte budget even when every label uses its full 64-byte allowance.
64/// This does not authenticate authority or change the existing signed encoding.
65pub fn validate_credential_grants(
66    grants: &[DelegatedRoleGrant],
67) -> Result<(), PortableEncodingError> {
68    credential_grants(grants).map(|_| ())
69}
70
71fn credential_grants(
72    grants: &[DelegatedRoleGrant],
73) -> Result<CheckedGrants<'_>, PortableEncodingError> {
74    let checked = CheckedGrants::bounded(grants, MAX_GRANTS, MAX_SCOPES_PER_GRANT)?;
75    check_scope_entries(grants.iter().map(|grant| grant.scopes.len()).sum())?;
76    // Count with the canonical encoder: no second size formula, allocation or
77    // change to signed bytes. Cardinality and label bounds already cap this sum.
78    let mut length = 0;
79    checked.encode(&mut |part| length += part.len())?;
80    if length > MAX_CREDENTIAL_GRANT_BYTES {
81        return Err(PortableEncodingError::TooLarge);
82    }
83    Ok(checked)
84}
85
86fn check_scope_entries(found: usize) -> Result<(), PortableEncodingError> {
87    if found > MAX_CREDENTIAL_SCOPE_ENTRIES {
88        return Err(PortableEncodingError::TooManyScopeEntries {
89            found,
90            max: MAX_CREDENTIAL_SCOPE_ENTRIES,
91        });
92    }
93    Ok(())
94}
95
96/// Structural codec errors, never proof-verification outcomes.
97#[derive(Debug, Error, PartialEq, Eq)]
98pub enum PortableEncodingError {
99    #[error("portable claims exceed their byte bound")]
100    /// Claims or canonical grant-list bytes exceed the admitted bound.
101    TooLarge,
102    #[error("credential has {found} scope entries; maximum is {max}")]
103    /// Total scope entries across all roles exceed the credential's aggregate bound.
104    TooManyScopeEntries {
105        /// Submitted entries, counting a scope once for each role containing it.
106        found: usize,
107        /// Inclusive aggregate scope-entry ceiling.
108        max: usize,
109    },
110    #[error("truncated portable claims")]
111    /// Input ended before a complete canonical field was available.
112    Truncated,
113    #[error("wrong portable domain, schema or mechanism")]
114    /// Domain, schema or mechanism discriminator is not supported.
115    WrongDomain,
116    #[error("portable claims contain trailing bytes")]
117    /// Extra input follows the complete canonical claims record.
118    TrailingBytes,
119    #[error("invalid portable principal, label or count")]
120    /// An identity, label or count violates the claims structure.
121    InvalidShape,
122    #[error("anonymous account subject")]
123    /// The account subject is anonymous.
124    AnonymousSubject,
125    #[error(transparent)]
126    /// Grant shape or cardinality violates the portable contract.
127    Grants(#[from] GrantValidationError),
128    #[error(transparent)]
129    /// Labels or ordered grants fail canonical admission.
130    Canonical(#[from] CanonicalAuthError),
131}
132
133/// Encode the schema-2 device-fenced claims domain. Never sort or normalize input.
134/// Time relationships and protected authority are verification responsibilities.
135pub fn encode_claims(claims: &PortableClaims) -> Result<Vec<u8>, PortableEncodingError> {
136    let mut bytes = Vec::new();
137    encode_claims_into(claims, &mut |part| bytes.extend_from_slice(part))?;
138    Ok(bytes)
139}
140
141fn encode_claims_into(
142    claims: &PortableClaims,
143    sink: &mut crate::canonical::Sink<'_>,
144) -> Result<(), PortableEncodingError> {
145    let grants = validate_shape(claims)?;
146    encode_claims_fields(claims, &grants, sink)
147}
148
149// Integrity checking of already-completed issuer results keeps the historical
150// structural ceiling. This is not available to new issuance or verification.
151#[cfg(feature = "persistent")]
152pub(crate) fn encode_retained_claims(
153    claims: &PortableClaims,
154) -> Result<Vec<u8>, PortableEncodingError> {
155    validate_identity(claims)?;
156    let grants = CheckedGrants::bounded(&claims.grants, MAX_GRANTS, MAX_SCOPES_PER_GRANT)?;
157    let mut bytes = Vec::new();
158    encode_claims_fields(claims, &grants, &mut |part| bytes.extend_from_slice(part))?;
159    Ok(bytes)
160}
161
162fn encode_claims_fields(
163    claims: &PortableClaims,
164    grants: &CheckedGrants<'_>,
165    sink: &mut crate::canonical::Sink<'_>,
166) -> Result<(), PortableEncodingError> {
167    // The same bounded field traversal produces bytes or feeds SHA-256.
168    let mut length = 0usize;
169    let mut out = |bytes: &[u8]| {
170        length = length.saturating_add(bytes.len());
171        sink(bytes);
172    };
173    out(DOMAIN);
174    out(&SCHEMA.to_be_bytes());
175    out(&[match claims.mechanism {
176        PortableMechanism::Certified => 0,
177        PortableMechanism::Ed25519 => 1,
178    }]);
179    out(claims.audience.canonical_network_id.as_bytes());
180    out(claims.audience.fleet_id.as_bytes());
181    encode_principal(&mut out, claims.issuer)?;
182    out(&claims.key_binding_id);
183    out(&claims.browser_public_key);
184    encode_principal(&mut out, claims.account_subject)?;
185    out(&[claims.device_slot]);
186    out(&claims.device_generation.to_be_bytes());
187    for time in [
188        claims.login_started_at_ns,
189        claims.login_deadline_ns,
190        claims.issued_at_ns,
191        claims.admission_expires_at_ns,
192    ] {
193        out(&time.to_be_bytes());
194    }
195    out(&claims.nonce);
196    grants.encode(&mut out)?;
197    if length > MAX_CLAIMS_BYTES {
198        return Err(PortableEncodingError::TooLarge);
199    }
200    Ok(())
201}
202
203/// Decode bounded canonical claims. Lengths/counts are admitted before allocation;
204/// unknown schema/mechanism, trailing bytes and noncanonical grants are rejected.
205/// This is deliberately not a deserializer for the previous token domain.
206pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, PortableEncodingError> {
207    if bytes.len() > MAX_CLAIMS_BYTES {
208        return Err(PortableEncodingError::TooLarge);
209    }
210    let mut input = Reader(bytes);
211    if input.take(DOMAIN.len())? != DOMAIN || input.array::<2>()? != SCHEMA.to_be_bytes() {
212        return Err(PortableEncodingError::WrongDomain);
213    }
214    let mechanism = match input.array::<1>()? {
215        [0] => PortableMechanism::Certified,
216        [1] => PortableMechanism::Ed25519,
217        _ => return Err(PortableEncodingError::WrongDomain),
218    };
219    let audience = AudienceId {
220        canonical_network_id: CanonicalId::from_bytes(input.array()?),
221        fleet_id: CanonicalId::from_bytes(input.array()?),
222    };
223    let issuer = input.principal()?;
224    let key_binding_id = input.array()?;
225    let browser_public_key = input.array()?;
226    let account_subject = input.principal()?;
227    let [device_slot] = input.array()?;
228    let device_generation = u64::from_be_bytes(input.array()?);
229    let login_started_at_ns = u64::from_be_bytes(input.array()?);
230    let login_deadline_ns = u64::from_be_bytes(input.array()?);
231    let issued_at_ns = u64::from_be_bytes(input.array()?);
232    let admission_expires_at_ns = u64::from_be_bytes(input.array()?);
233    let nonce = input.array()?;
234    // The grant list is the remaining signed payload. Reject excess bytes before
235    // allocating labels or verifying a signature, even for malformed input.
236    if input.0.len() > MAX_CREDENTIAL_GRANT_BYTES {
237        return Err(PortableEncodingError::TooLarge);
238    }
239    let count = input.count(MAX_GRANTS)?;
240    let mut grants = Vec::with_capacity(count);
241    let mut scope_entries = 0;
242    for _ in 0..count {
243        let target = input
244            .label()?
245            .parse()
246            .map_err(|_| PortableEncodingError::InvalidShape)?;
247        let count = input.count(MAX_SCOPES_PER_GRANT)?;
248        scope_entries += count;
249        check_scope_entries(scope_entries)?;
250        let mut scopes = Vec::with_capacity(count);
251        for _ in 0..count {
252            scopes.push(
253                input
254                    .label()?
255                    .parse()
256                    .map_err(|_| PortableEncodingError::InvalidShape)?,
257            );
258        }
259        grants.push(DelegatedRoleGrant { target, scopes });
260    }
261    if !input.0.is_empty() {
262        return Err(PortableEncodingError::TrailingBytes);
263    }
264    let claims = PortableClaims {
265        mechanism,
266        audience,
267        issuer,
268        key_binding_id,
269        browser_public_key,
270        account_subject,
271        device_slot,
272        device_generation,
273        login_started_at_ns,
274        login_deadline_ns,
275        issued_at_ns,
276        admission_expires_at_ns,
277        nonce,
278        grants,
279    };
280    validate_shape(&claims)?;
281    Ok(claims)
282}
283
284/// SHA-256 of the exact canonical signed blob, for signing and replay identity.
285/// The digest authenticates nothing by itself; signature bytes are not included.
286pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], PortableEncodingError> {
287    let mut hash = Sha256::new();
288    encode_claims_into(claims, &mut |bytes| hash.update(bytes))?;
289    Ok(hash.finalize().into())
290}
291
292/// Derive the IC sender for a directly authenticated Ed25519 browser key.
293/// Hosts must compare this with the actual ingress caller, not a client field.
294/// This does not validate curve membership or possession of the key.
295#[must_use]
296pub fn browser_principal(public_key: &[u8; 32]) -> Principal {
297    // RFC 8410 Ed25519 SubjectPublicKeyInfo: SEQUENCE(algorithm OID, BIT STRING).
298    let mut der = [0; 44];
299    der[..12].copy_from_slice(&[
300        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0,
301    ]);
302    der[12..].copy_from_slice(public_key);
303    Principal::self_authenticating(der)
304}
305
306// A login caller must have the complete self-authenticating principal shape.
307// This checks neither ingress provenance nor possession of the browser key.
308pub(crate) fn is_login_caller(caller: Principal) -> bool {
309    let bytes = caller.as_slice();
310    bytes.len() == 29 && bytes.last() == Some(&2)
311}
312
313fn validate_shape(claims: &PortableClaims) -> Result<CheckedGrants<'_>, PortableEncodingError> {
314    validate_identity(claims)?;
315    credential_grants(&claims.grants)
316}
317
318fn validate_identity(claims: &PortableClaims) -> Result<(), PortableEncodingError> {
319    if claims.device_slot >= ic_auth_protocol_types::limits::MAX_DEVICE_SLOTS
320        || claims.device_generation == 0
321    {
322        return Err(PortableEncodingError::InvalidShape);
323    }
324    if claims.account_subject == Principal::anonymous() {
325        return Err(PortableEncodingError::AnonymousSubject);
326    }
327    Ok(())
328}
329
330struct Reader<'a>(&'a [u8]);
331
332impl<'a> Reader<'a> {
333    fn take(&mut self, len: usize) -> Result<&'a [u8], PortableEncodingError> {
334        let (head, tail) = self
335            .0
336            .split_at_checked(len)
337            .ok_or(PortableEncodingError::Truncated)?;
338        self.0 = tail;
339        Ok(head)
340    }
341
342    fn array<const N: usize>(&mut self) -> Result<[u8; N], PortableEncodingError> {
343        self.take(N)?
344            .try_into()
345            .map_err(|_| PortableEncodingError::Truncated)
346    }
347
348    fn length(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
349        let len = u32::from_be_bytes(self.array()?);
350        let len = usize::try_from(len).map_err(|_| PortableEncodingError::InvalidShape)?;
351        if len > max {
352            return Err(PortableEncodingError::InvalidShape);
353        }
354        Ok(len)
355    }
356
357    fn count(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
358        let count = self.length(max)?;
359        if count == 0 {
360            return Err(PortableEncodingError::InvalidShape);
361        }
362        Ok(count)
363    }
364
365    fn principal(&mut self) -> Result<Principal, PortableEncodingError> {
366        let len = self.length(29)?;
367        Ok(Principal::from_slice(self.take(len)?))
368    }
369
370    fn label(&mut self) -> Result<&'a str, PortableEncodingError> {
371        let len = self.count(MAX_LABEL_BYTES)?;
372        std::str::from_utf8(self.take(len)?).map_err(|_| PortableEncodingError::InvalidShape)
373    }
374}
375
376#[cfg(test)]
377mod tests;