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    TooLarge,
101    #[error("credential has {found} scope entries; maximum is {max}")]
102    TooManyScopeEntries { found: usize, max: usize },
103    #[error("truncated portable claims")]
104    Truncated,
105    #[error("wrong portable domain, schema or mechanism")]
106    WrongDomain,
107    #[error("portable claims contain trailing bytes")]
108    TrailingBytes,
109    #[error("invalid portable principal, label or count")]
110    InvalidShape,
111    #[error("anonymous account subject")]
112    AnonymousSubject,
113    #[error(transparent)]
114    Grants(#[from] GrantValidationError),
115    #[error(transparent)]
116    Canonical(#[from] CanonicalAuthError),
117}
118
119/// Encode the schema-2 device-fenced claims domain. Never sort or normalize input.
120/// Time relationships and protected authority are verification responsibilities.
121pub fn encode_claims(claims: &PortableClaims) -> Result<Vec<u8>, PortableEncodingError> {
122    let mut bytes = Vec::new();
123    encode_claims_into(claims, &mut |part| bytes.extend_from_slice(part))?;
124    Ok(bytes)
125}
126
127fn encode_claims_into(
128    claims: &PortableClaims,
129    sink: &mut crate::canonical::Sink<'_>,
130) -> Result<(), PortableEncodingError> {
131    let grants = validate_shape(claims)?;
132    encode_claims_fields(claims, grants, sink)
133}
134
135// Integrity checking of already-completed issuer results keeps the historical
136// structural ceiling. This is not available to new issuance or verification.
137#[cfg(feature = "persistent")]
138pub(crate) fn encode_retained_claims(
139    claims: &PortableClaims,
140) -> Result<Vec<u8>, PortableEncodingError> {
141    validate_identity(claims)?;
142    let grants = CheckedGrants::bounded(&claims.grants, MAX_GRANTS, MAX_SCOPES_PER_GRANT)?;
143    let mut bytes = Vec::new();
144    encode_claims_fields(claims, grants, &mut |part| bytes.extend_from_slice(part))?;
145    Ok(bytes)
146}
147
148fn encode_claims_fields(
149    claims: &PortableClaims,
150    grants: CheckedGrants<'_>,
151    sink: &mut crate::canonical::Sink<'_>,
152) -> Result<(), PortableEncodingError> {
153    // The same bounded field traversal produces bytes or feeds SHA-256.
154    let mut length = 0usize;
155    let mut out = |bytes: &[u8]| {
156        length = length.saturating_add(bytes.len());
157        sink(bytes);
158    };
159    out(DOMAIN);
160    out(&SCHEMA.to_be_bytes());
161    out(&[match claims.mechanism {
162        PortableMechanism::Certified => 0,
163        PortableMechanism::Ed25519 => 1,
164    }]);
165    out(claims.audience.canonical_network_id.as_bytes());
166    out(claims.audience.fleet_id.as_bytes());
167    encode_principal(&mut out, claims.issuer)?;
168    out(&claims.key_binding_id);
169    out(&claims.browser_public_key);
170    encode_principal(&mut out, claims.account_subject)?;
171    out(&[claims.device_slot]);
172    out(&claims.device_generation.to_be_bytes());
173    for time in [
174        claims.login_started_at_ns,
175        claims.login_deadline_ns,
176        claims.issued_at_ns,
177        claims.admission_expires_at_ns,
178    ] {
179        out(&time.to_be_bytes());
180    }
181    out(&claims.nonce);
182    grants.encode(&mut out)?;
183    if length > MAX_CLAIMS_BYTES {
184        return Err(PortableEncodingError::TooLarge);
185    }
186    Ok(())
187}
188
189/// Decode bounded canonical claims. Lengths/counts are admitted before allocation;
190/// unknown schema/mechanism, trailing bytes and noncanonical grants are rejected.
191/// This is deliberately not a deserializer for the previous token domain.
192pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, PortableEncodingError> {
193    if bytes.len() > MAX_CLAIMS_BYTES {
194        return Err(PortableEncodingError::TooLarge);
195    }
196    let mut input = Reader(bytes);
197    if input.take(DOMAIN.len())? != DOMAIN || input.array::<2>()? != SCHEMA.to_be_bytes() {
198        return Err(PortableEncodingError::WrongDomain);
199    }
200    let mechanism = match input.array::<1>()? {
201        [0] => PortableMechanism::Certified,
202        [1] => PortableMechanism::Ed25519,
203        _ => return Err(PortableEncodingError::WrongDomain),
204    };
205    let audience = AudienceId {
206        canonical_network_id: CanonicalId::from_bytes(input.array()?),
207        fleet_id: CanonicalId::from_bytes(input.array()?),
208    };
209    let issuer = input.principal()?;
210    let key_binding_id = input.array()?;
211    let browser_public_key = input.array()?;
212    let account_subject = input.principal()?;
213    let [device_slot] = input.array()?;
214    let device_generation = u64::from_be_bytes(input.array()?);
215    let login_started_at_ns = u64::from_be_bytes(input.array()?);
216    let login_deadline_ns = u64::from_be_bytes(input.array()?);
217    let issued_at_ns = u64::from_be_bytes(input.array()?);
218    let admission_expires_at_ns = u64::from_be_bytes(input.array()?);
219    let nonce = input.array()?;
220    // The grant list is the remaining signed payload. Reject excess bytes before
221    // allocating labels or verifying a signature, even for malformed input.
222    if input.0.len() > MAX_CREDENTIAL_GRANT_BYTES {
223        return Err(PortableEncodingError::TooLarge);
224    }
225    let count = input.count(MAX_GRANTS)?;
226    let mut grants = Vec::with_capacity(count);
227    let mut scope_entries = 0;
228    for _ in 0..count {
229        let target = input
230            .label()?
231            .parse()
232            .map_err(|_| PortableEncodingError::InvalidShape)?;
233        let count = input.count(MAX_SCOPES_PER_GRANT)?;
234        scope_entries += count;
235        check_scope_entries(scope_entries)?;
236        let mut scopes = Vec::with_capacity(count);
237        for _ in 0..count {
238            scopes.push(
239                input
240                    .label()?
241                    .parse()
242                    .map_err(|_| PortableEncodingError::InvalidShape)?,
243            );
244        }
245        grants.push(DelegatedRoleGrant { target, scopes });
246    }
247    if !input.0.is_empty() {
248        return Err(PortableEncodingError::TrailingBytes);
249    }
250    let claims = PortableClaims {
251        mechanism,
252        audience,
253        issuer,
254        key_binding_id,
255        browser_public_key,
256        account_subject,
257        device_slot,
258        device_generation,
259        login_started_at_ns,
260        login_deadline_ns,
261        issued_at_ns,
262        admission_expires_at_ns,
263        nonce,
264        grants,
265    };
266    validate_shape(&claims)?;
267    Ok(claims)
268}
269
270/// SHA-256 of the exact canonical signed blob, for signing and replay identity.
271/// The digest authenticates nothing by itself; signature bytes are not included.
272pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], PortableEncodingError> {
273    let mut hash = Sha256::new();
274    encode_claims_into(claims, &mut |bytes| hash.update(bytes))?;
275    Ok(hash.finalize().into())
276}
277
278/// Derive the IC sender for a directly authenticated Ed25519 browser key.
279/// Hosts must compare this with the actual ingress caller, not a client field.
280/// This does not validate curve membership or possession of the key.
281pub fn browser_principal(public_key: &[u8; 32]) -> Principal {
282    // RFC 8410 Ed25519 SubjectPublicKeyInfo: SEQUENCE(algorithm OID, BIT STRING).
283    let mut der = [0; 44];
284    der[..12].copy_from_slice(&[
285        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0,
286    ]);
287    der[12..].copy_from_slice(public_key);
288    Principal::self_authenticating(der)
289}
290
291// A login caller must have the complete self-authenticating principal shape.
292// This checks neither ingress provenance nor possession of the browser key.
293pub(crate) fn is_login_caller(caller: Principal) -> bool {
294    let bytes = caller.as_slice();
295    bytes.len() == 29 && bytes.last() == Some(&2)
296}
297
298fn validate_shape(claims: &PortableClaims) -> Result<CheckedGrants<'_>, PortableEncodingError> {
299    validate_identity(claims)?;
300    credential_grants(&claims.grants)
301}
302
303fn validate_identity(claims: &PortableClaims) -> Result<(), PortableEncodingError> {
304    if claims.device_slot >= ic_auth_protocol_types::limits::MAX_DEVICE_SLOTS
305        || claims.device_generation == 0
306    {
307        return Err(PortableEncodingError::InvalidShape);
308    }
309    if claims.account_subject == Principal::anonymous() {
310        return Err(PortableEncodingError::AnonymousSubject);
311    }
312    Ok(())
313}
314
315struct Reader<'a>(&'a [u8]);
316
317impl<'a> Reader<'a> {
318    fn take(&mut self, len: usize) -> Result<&'a [u8], PortableEncodingError> {
319        let (head, tail) = self
320            .0
321            .split_at_checked(len)
322            .ok_or(PortableEncodingError::Truncated)?;
323        self.0 = tail;
324        Ok(head)
325    }
326
327    fn array<const N: usize>(&mut self) -> Result<[u8; N], PortableEncodingError> {
328        self.take(N)?
329            .try_into()
330            .map_err(|_| PortableEncodingError::Truncated)
331    }
332
333    fn length(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
334        let len = u32::from_be_bytes(self.array()?);
335        let len = usize::try_from(len).map_err(|_| PortableEncodingError::InvalidShape)?;
336        if len > max {
337            return Err(PortableEncodingError::InvalidShape);
338        }
339        Ok(len)
340    }
341
342    fn count(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
343        let count = self.length(max)?;
344        if count == 0 {
345            return Err(PortableEncodingError::InvalidShape);
346        }
347        Ok(count)
348    }
349
350    fn principal(&mut self) -> Result<Principal, PortableEncodingError> {
351        let len = self.length(29)?;
352        Ok(Principal::from_slice(self.take(len)?))
353    }
354
355    fn label(&mut self) -> Result<&'a str, PortableEncodingError> {
356        let len = self.count(MAX_LABEL_BYTES)?;
357        std::str::from_utf8(self.take(len)?).map_err(|_| PortableEncodingError::InvalidShape)
358    }
359}
360
361#[cfg(test)]
362mod tests;