Skip to main content

ic_auth/
claims.rs

1//! Bounded schema-2 signed bytes. Decode, encode and hashing grant no authority.
2//!
3//! Only the current fresh-credential format is supported. Signed labels remain
4//! in supplied order; unlike unsigned session requests, they are never sorted.
5
6use ic_auth_protocol_types::{
7    AudienceId, CanonicalId, DelegatedRoleGrant, PortableClaims, PortableMechanism, Principal,
8};
9use sha2::{Digest, Sha256};
10use std::{error::Error, fmt};
11
12const DOMAIN: &[u8] = b"IC-AUTH-PORTABLE-CREDENTIAL\0";
13const SCHEMA: u16 = 2;
14const MAX_ROLES: usize = 16;
15const MAX_SCOPES_PER_ROLE: usize = 32;
16const MAX_SCOPE_ENTRIES: usize = 32;
17const MAX_LABEL_BYTES: usize = 64;
18const MAX_GRANT_BYTES: usize = 4096;
19
20/// Signed-claims byte ceiling, independent of the outer Wire and proof budgets.
21pub const MAX_CLAIMS_BYTES: usize = 65_536;
22
23// Bounded labels/counts imply the complete grant list fits without measuring it
24// with another encoder. Principal lengths and all other fields are fixed/bounded.
25const _: () = assert!(
26    4 + MAX_ROLES * (8 + MAX_LABEL_BYTES) + MAX_SCOPE_ENTRIES * (4 + MAX_LABEL_BYTES)
27        <= MAX_GRANT_BYTES
28);
29// The schema-2 prefix is at most 282 bytes with two maximum-length principals.
30const _: () = assert!(282 + MAX_GRANT_BYTES <= MAX_CLAIMS_BYTES);
31
32///
33/// ClaimsError
34///
35/// Structural rejection, distinct from signature, time and enrollment failures.
36///
37
38#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub enum ClaimsError {
40    /// The entire blob or remaining grant payload exceeds its defensive byte cap.
41    TooLarge,
42    /// A required field is incomplete.
43    Truncated,
44    /// Domain, schema or mechanism is unsupported; no legacy fallback is tried.
45    WrongDomain,
46    /// Data follows the complete record.
47    TrailingBytes,
48    /// A length, label, principal or device fence is structurally invalid.
49    InvalidShape,
50    /// The claimed account subject is anonymous.
51    AnonymousSubject,
52    /// Roles are duplicated or not strictly ascending.
53    NonCanonicalRoles,
54    /// Scopes within a role are duplicated or not strictly ascending.
55    NonCanonicalScopes,
56    /// The in-memory grant list is empty or exceeds 16 roles.
57    InvalidGrantCount {
58        /// Submitted number of grants.
59        found: usize,
60    },
61    /// An in-memory role has no scopes or exceeds 32 scopes.
62    InvalidScopeCount {
63        /// Submitted number of scopes in that role.
64        found: usize,
65    },
66    /// The total number of role–scope entries exceeds the fresh-credential cap.
67    TooManyScopeEntries {
68        /// Cumulative entries, counting the same label under each role separately.
69        found: usize,
70        /// Inclusive entry ceiling.
71        max: usize,
72    },
73}
74
75impl fmt::Display for ClaimsError {
76    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
77        let message = match self {
78            Self::TooLarge => "claims exceed their byte bound",
79            Self::Truncated => "truncated claims",
80            Self::WrongDomain => "unsupported claims domain, schema or mechanism",
81            Self::TrailingBytes => "trailing claims bytes",
82            Self::InvalidShape => "invalid claims structure",
83            Self::AnonymousSubject => "anonymous account subject",
84            Self::NonCanonicalRoles => "roles must be strictly ordered and unique",
85            Self::NonCanonicalScopes => "scopes must be strictly ordered and unique",
86            Self::InvalidGrantCount { found } => {
87                return write!(f, "grant count {found} is outside 1..=16");
88            }
89            Self::InvalidScopeCount { found } => {
90                return write!(f, "scope count {found} is outside 1..=32");
91            }
92            Self::TooManyScopeEntries { found, max } => {
93                return write!(f, "credential has {found} scope entries; maximum is {max}");
94            }
95        };
96        f.write_str(message)
97    }
98}
99
100impl Error for ClaimsError {}
101
102fn check_entries(found: usize) -> Result<(), ClaimsError> {
103    if found > MAX_SCOPE_ENTRIES {
104        return Err(ClaimsError::TooManyScopeEntries {
105            found,
106            max: MAX_SCOPE_ENTRIES,
107        });
108    }
109    Ok(())
110}
111
112fn validate(claims: &PortableClaims) -> Result<(), ClaimsError> {
113    if claims.device_slot > 7 || claims.device_generation == 0 {
114        return Err(ClaimsError::InvalidShape);
115    }
116    if claims.account_subject == Principal::anonymous() {
117        return Err(ClaimsError::AnonymousSubject);
118    }
119    validate_grants(&claims.grants)?;
120    check_entries(claims.grants.iter().map(|grant| grant.scopes.len()).sum())
121}
122
123// Protected authority may contain 32 scopes for each of 16 roles. Fresh
124// credentials separately enforce the narrower aggregate 32-entry ceiling.
125pub(crate) fn validate_grants(grants: &[DelegatedRoleGrant]) -> Result<(), ClaimsError> {
126    if !(1..=MAX_ROLES).contains(&grants.len()) {
127        return Err(ClaimsError::InvalidGrantCount {
128            found: grants.len(),
129        });
130    }
131    for (index, grant) in grants.iter().enumerate() {
132        if index > 0 && grants[index - 1].target >= grant.target {
133            return Err(ClaimsError::NonCanonicalRoles);
134        }
135        if !(1..=MAX_SCOPES_PER_ROLE).contains(&grant.scopes.len()) {
136            return Err(ClaimsError::InvalidScopeCount {
137                found: grant.scopes.len(),
138            });
139        }
140        if grant.scopes.windows(2).any(|pair| pair[0] >= pair[1]) {
141            return Err(ClaimsError::NonCanonicalScopes);
142        }
143    }
144    Ok(())
145}
146
147/// Encode current canonical claims after checking all structural invariants.
148///
149/// Labels are not normalized. Time relationships and trust require the complete
150/// verifier; a valid encoding may describe an expired or unauthorized credential.
151pub fn encode_claims(claims: &PortableClaims) -> Result<Vec<u8>, ClaimsError> {
152    validate(claims)?;
153    let mut output = Vec::new();
154    write_fields(claims, |bytes| output.extend_from_slice(bytes));
155    Ok(output)
156}
157
158/// Hash the exact canonical claims bytes with SHA-256, excluding proof material.
159///
160/// This performs the same shape checks as encoding and streams directly into
161/// the published hash implementation. A digest is not verification evidence.
162pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], ClaimsError> {
163    validate(claims)?;
164    let mut digest = Sha256::new();
165    write_fields(claims, |bytes| digest.update(bytes));
166    Ok(digest.finalize().into())
167}
168
169// One private field traversal owns the signed layout for encoding and hashing.
170// Callers validate first; all casts are bounded by that admission or Principal.
171fn write_fields(claims: &PortableClaims, mut emit: impl FnMut(&[u8])) {
172    emit(DOMAIN);
173    emit(&SCHEMA.to_be_bytes());
174    emit(&[match claims.mechanism {
175        PortableMechanism::Certified => 0,
176        PortableMechanism::Ed25519 => 1,
177    }]);
178    emit(claims.audience.canonical_network_id.as_bytes());
179    emit(claims.audience.fleet_id.as_bytes());
180    emit(&(u32::from(claims.issuer.len())).to_be_bytes());
181    emit(claims.issuer.as_slice());
182    emit(&claims.key_binding_id);
183    emit(&claims.browser_public_key);
184    emit(&(u32::from(claims.account_subject.len())).to_be_bytes());
185    emit(claims.account_subject.as_slice());
186    emit(&[claims.device_slot]);
187    for value in [
188        claims.device_generation,
189        claims.login_started_at_ns,
190        claims.login_deadline_ns,
191        claims.issued_at_ns,
192        claims.admission_expires_at_ns,
193    ] {
194        emit(&value.to_be_bytes());
195    }
196    emit(&claims.nonce);
197    write_grants(&claims.grants, &mut emit);
198}
199
200// Canonical claims and root delegations share the same admitted grant layout.
201// Both callers validate counts/order before emitting any bytes.
202pub(crate) fn write_grants(grants: &[DelegatedRoleGrant], emit: &mut dyn FnMut(&[u8])) {
203    emit(&(grants.len() as u32).to_be_bytes());
204    for grant in grants {
205        emit(&(grant.target.as_str().len() as u32).to_be_bytes());
206        emit(grant.target.as_str().as_bytes());
207        emit(&(grant.scopes.len() as u32).to_be_bytes());
208        for scope in &grant.scopes {
209            emit(&(scope.as_str().len() as u32).to_be_bytes());
210            emit(scope.as_str().as_bytes());
211        }
212    }
213}
214
215/// Decode one bounded canonical schema-2 record, without granting authority.
216///
217/// Count and byte limits are admitted before allocating their values. Extra
218/// bytes, unknown formats and noncanonical signed order refuse without repair.
219pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, ClaimsError> {
220    if bytes.len() > MAX_CLAIMS_BYTES {
221        return Err(ClaimsError::TooLarge);
222    }
223    let mut input = Input { remaining: bytes };
224    if input.take(DOMAIN.len())? != DOMAIN || u16::from_be_bytes(input.fixed()?) != SCHEMA {
225        return Err(ClaimsError::WrongDomain);
226    }
227    let mechanism = match input.fixed()? {
228        [0] => PortableMechanism::Certified,
229        [1] => PortableMechanism::Ed25519,
230        _ => return Err(ClaimsError::WrongDomain),
231    };
232    let audience = AudienceId {
233        canonical_network_id: CanonicalId::from_bytes(input.fixed()?),
234        fleet_id: CanonicalId::from_bytes(input.fixed()?),
235    };
236    let issuer = input.principal()?;
237    let key_binding_id = input.fixed()?;
238    let browser_public_key = input.fixed()?;
239    let account_subject = input.principal()?;
240    let [device_slot] = input.fixed()?;
241    let device_generation = u64::from_be_bytes(input.fixed()?);
242    let login_started_at_ns = u64::from_be_bytes(input.fixed()?);
243    let login_deadline_ns = u64::from_be_bytes(input.fixed()?);
244    let issued_at_ns = u64::from_be_bytes(input.fixed()?);
245    let admission_expires_at_ns = u64::from_be_bytes(input.fixed()?);
246    let nonce = input.fixed()?;
247    // The remaining bytes include the whole grant list and any trailing input.
248    if input.remaining.len() > MAX_GRANT_BYTES {
249        return Err(ClaimsError::TooLarge);
250    }
251    let roles = input.size(1, MAX_ROLES)?;
252    let mut grants = Vec::with_capacity(roles);
253    let mut entries = 0;
254    for _ in 0..roles {
255        let target = input
256            .label()?
257            .parse()
258            .map_err(|_| ClaimsError::InvalidShape)?;
259        let count = input.size(1, MAX_SCOPES_PER_ROLE)?;
260        entries += count;
261        check_entries(entries)?;
262        let mut scopes = Vec::with_capacity(count);
263        for _ in 0..count {
264            scopes.push(
265                input
266                    .label()?
267                    .parse()
268                    .map_err(|_| ClaimsError::InvalidShape)?,
269            );
270        }
271        grants.push(DelegatedRoleGrant { target, scopes });
272    }
273    if !input.remaining.is_empty() {
274        return Err(ClaimsError::TrailingBytes);
275    }
276    let claims = PortableClaims {
277        mechanism,
278        audience,
279        issuer,
280        key_binding_id,
281        browser_public_key,
282        account_subject,
283        device_slot,
284        device_generation,
285        login_started_at_ns,
286        login_deadline_ns,
287        issued_at_ns,
288        admission_expires_at_ns,
289        nonce,
290        grants,
291    };
292    validate(&claims)?;
293    Ok(claims)
294}
295
296// Claims-only cursor: borrowed slices and checked fixed-width lengths, no generic
297// serialization or storage framework. Failed reads never publish a partial value.
298
299///
300/// Input
301///
302/// Tracks the unconsumed suffix of the claims encoding.
303///
304
305struct Input<'a> {
306    remaining: &'a [u8],
307}
308
309impl<'a> Input<'a> {
310    fn take(&mut self, length: usize) -> Result<&'a [u8], ClaimsError> {
311        let head = self.remaining.get(..length).ok_or(ClaimsError::Truncated)?;
312        self.remaining = &self.remaining[length..];
313        Ok(head)
314    }
315
316    fn fixed<const N: usize>(&mut self) -> Result<[u8; N], ClaimsError> {
317        self.take(N)?.try_into().map_err(|_| ClaimsError::Truncated)
318    }
319
320    fn size(&mut self, minimum: usize, maximum: usize) -> Result<usize, ClaimsError> {
321        let size = usize::try_from(u32::from_be_bytes(self.fixed()?))
322            .map_err(|_| ClaimsError::InvalidShape)?;
323        if !(minimum..=maximum).contains(&size) {
324            return Err(ClaimsError::InvalidShape);
325        }
326        Ok(size)
327    }
328
329    fn principal(&mut self) -> Result<Principal, ClaimsError> {
330        let size = self.size(0, Principal::MAX_LENGTH_IN_BYTES)?;
331        Principal::try_from_slice(self.take(size)?).map_err(|_| ClaimsError::InvalidShape)
332    }
333
334    fn label(&mut self) -> Result<&'a str, ClaimsError> {
335        let size = self.size(1, MAX_LABEL_BYTES)?;
336        std::str::from_utf8(self.take(size)?).map_err(|_| ClaimsError::InvalidShape)
337    }
338}