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/// Structural codec errors, never proof-verification outcomes.
46#[derive(Debug, Error, PartialEq, Eq)]
47pub enum PortableEncodingError {
48    #[error("portable claims exceed their byte bound")]
49    TooLarge,
50    #[error("truncated portable claims")]
51    Truncated,
52    #[error("wrong portable domain, schema or mechanism")]
53    WrongDomain,
54    #[error("portable claims contain trailing bytes")]
55    TrailingBytes,
56    #[error("invalid portable principal, label or count")]
57    InvalidShape,
58    #[error("anonymous account subject")]
59    AnonymousSubject,
60    #[error(transparent)]
61    Grants(#[from] GrantValidationError),
62    #[error(transparent)]
63    Canonical(#[from] CanonicalAuthError),
64}
65
66/// Encode the schema-2 device-fenced claims domain. Never sort or normalize input.
67/// Time relationships and protected authority are verification responsibilities.
68pub fn encode_claims(claims: &PortableClaims) -> Result<Vec<u8>, PortableEncodingError> {
69    let mut bytes = Vec::new();
70    encode_claims_into(claims, &mut |part| bytes.extend_from_slice(part))?;
71    Ok(bytes)
72}
73
74fn encode_claims_into(
75    claims: &PortableClaims,
76    sink: &mut crate::canonical::Sink<'_>,
77) -> Result<(), PortableEncodingError> {
78    let grants = validate_shape(claims)?;
79    // The same bounded field traversal produces bytes or feeds SHA-256.
80    let mut length = 0usize;
81    let mut out = |bytes: &[u8]| {
82        length = length.saturating_add(bytes.len());
83        sink(bytes);
84    };
85    out(DOMAIN);
86    out(&SCHEMA.to_be_bytes());
87    out(&[match claims.mechanism {
88        PortableMechanism::Certified => 0,
89        PortableMechanism::Ed25519 => 1,
90    }]);
91    out(claims.audience.canonical_network_id.as_bytes());
92    out(claims.audience.fleet_id.as_bytes());
93    encode_principal(&mut out, claims.issuer)?;
94    out(&claims.key_binding_id);
95    out(&claims.browser_public_key);
96    encode_principal(&mut out, claims.account_subject)?;
97    out(&[claims.device_slot]);
98    out(&claims.device_generation.to_be_bytes());
99    for time in [
100        claims.login_started_at_ns,
101        claims.login_deadline_ns,
102        claims.issued_at_ns,
103        claims.admission_expires_at_ns,
104    ] {
105        out(&time.to_be_bytes());
106    }
107    out(&claims.nonce);
108    grants.encode(&mut out)?;
109    if length > MAX_CLAIMS_BYTES {
110        return Err(PortableEncodingError::TooLarge);
111    }
112    Ok(())
113}
114
115/// Decode bounded canonical claims. Lengths/counts are admitted before allocation;
116/// unknown schema/mechanism, trailing bytes and noncanonical grants are rejected.
117/// This is deliberately not a deserializer for the previous token domain.
118pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, PortableEncodingError> {
119    if bytes.len() > MAX_CLAIMS_BYTES {
120        return Err(PortableEncodingError::TooLarge);
121    }
122    let mut input = Reader(bytes);
123    if input.take(DOMAIN.len())? != DOMAIN || input.array::<2>()? != SCHEMA.to_be_bytes() {
124        return Err(PortableEncodingError::WrongDomain);
125    }
126    let mechanism = match input.array::<1>()? {
127        [0] => PortableMechanism::Certified,
128        [1] => PortableMechanism::Ed25519,
129        _ => return Err(PortableEncodingError::WrongDomain),
130    };
131    let audience = AudienceId {
132        canonical_network_id: CanonicalId::from_bytes(input.array()?),
133        fleet_id: CanonicalId::from_bytes(input.array()?),
134    };
135    let issuer = input.principal()?;
136    let key_binding_id = input.array()?;
137    let browser_public_key = input.array()?;
138    let account_subject = input.principal()?;
139    let [device_slot] = input.array()?;
140    let device_generation = u64::from_be_bytes(input.array()?);
141    let login_started_at_ns = u64::from_be_bytes(input.array()?);
142    let login_deadline_ns = u64::from_be_bytes(input.array()?);
143    let issued_at_ns = u64::from_be_bytes(input.array()?);
144    let admission_expires_at_ns = u64::from_be_bytes(input.array()?);
145    let nonce = input.array()?;
146    let count = input.count(MAX_GRANTS)?;
147    let mut grants = Vec::with_capacity(count);
148    for _ in 0..count {
149        let target = input
150            .label()?
151            .parse()
152            .map_err(|_| PortableEncodingError::InvalidShape)?;
153        let count = input.count(MAX_SCOPES_PER_GRANT)?;
154        let mut scopes = Vec::with_capacity(count);
155        for _ in 0..count {
156            scopes.push(
157                input
158                    .label()?
159                    .parse()
160                    .map_err(|_| PortableEncodingError::InvalidShape)?,
161            );
162        }
163        grants.push(DelegatedRoleGrant { target, scopes });
164    }
165    if !input.0.is_empty() {
166        return Err(PortableEncodingError::TrailingBytes);
167    }
168    let claims = PortableClaims {
169        mechanism,
170        audience,
171        issuer,
172        key_binding_id,
173        browser_public_key,
174        account_subject,
175        device_slot,
176        device_generation,
177        login_started_at_ns,
178        login_deadline_ns,
179        issued_at_ns,
180        admission_expires_at_ns,
181        nonce,
182        grants,
183    };
184    validate_shape(&claims)?;
185    Ok(claims)
186}
187
188/// SHA-256 of the exact canonical signed blob, for signing and replay identity.
189/// The digest authenticates nothing by itself; signature bytes are not included.
190pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], PortableEncodingError> {
191    let mut hash = Sha256::new();
192    encode_claims_into(claims, &mut |bytes| hash.update(bytes))?;
193    Ok(hash.finalize().into())
194}
195
196/// Derive the IC sender for a directly authenticated Ed25519 browser key.
197/// Hosts must compare this with the actual ingress caller, not a client field.
198/// This does not validate curve membership or possession of the key.
199pub fn browser_principal(public_key: &[u8; 32]) -> Principal {
200    // RFC 8410 Ed25519 SubjectPublicKeyInfo: SEQUENCE(algorithm OID, BIT STRING).
201    let mut der = [0; 44];
202    der[..12].copy_from_slice(&[
203        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0,
204    ]);
205    der[12..].copy_from_slice(public_key);
206    Principal::self_authenticating(der)
207}
208
209// A login caller must have the complete self-authenticating principal shape.
210// This checks neither ingress provenance nor possession of the browser key.
211pub(crate) fn is_login_caller(caller: Principal) -> bool {
212    let bytes = caller.as_slice();
213    bytes.len() == 29 && bytes.last() == Some(&2)
214}
215
216fn validate_shape(claims: &PortableClaims) -> Result<CheckedGrants<'_>, PortableEncodingError> {
217    if claims.device_slot >= ic_auth_protocol_types::limits::MAX_DEVICE_SLOTS
218        || claims.device_generation == 0
219    {
220        return Err(PortableEncodingError::InvalidShape);
221    }
222    if claims.account_subject == Principal::anonymous() {
223        return Err(PortableEncodingError::AnonymousSubject);
224    }
225    Ok(CheckedGrants::bounded(
226        &claims.grants,
227        MAX_GRANTS,
228        MAX_SCOPES_PER_GRANT,
229    )?)
230}
231
232struct Reader<'a>(&'a [u8]);
233
234impl<'a> Reader<'a> {
235    fn take(&mut self, len: usize) -> Result<&'a [u8], PortableEncodingError> {
236        let (head, tail) = self
237            .0
238            .split_at_checked(len)
239            .ok_or(PortableEncodingError::Truncated)?;
240        self.0 = tail;
241        Ok(head)
242    }
243
244    fn array<const N: usize>(&mut self) -> Result<[u8; N], PortableEncodingError> {
245        self.take(N)?
246            .try_into()
247            .map_err(|_| PortableEncodingError::Truncated)
248    }
249
250    fn length(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
251        let len = u32::from_be_bytes(self.array()?);
252        let len = usize::try_from(len).map_err(|_| PortableEncodingError::InvalidShape)?;
253        if len > max {
254            return Err(PortableEncodingError::InvalidShape);
255        }
256        Ok(len)
257    }
258
259    fn count(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
260        let count = self.length(max)?;
261        if count == 0 {
262            return Err(PortableEncodingError::InvalidShape);
263        }
264        Ok(count)
265    }
266
267    fn principal(&mut self) -> Result<Principal, PortableEncodingError> {
268        let len = self.length(29)?;
269        Ok(Principal::from_slice(self.take(len)?))
270    }
271
272    fn label(&mut self) -> Result<&'a str, PortableEncodingError> {
273        let len = self.count(MAX_LABEL_BYTES)?;
274        std::str::from_utf8(self.take(len)?).map_err(|_| PortableEncodingError::InvalidShape)
275    }
276}
277
278#[cfg(test)]
279mod tests;