Skip to main content

ic_auth/
portable.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 = 1;
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 exactly the frozen 0.6 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    for time in [
98        claims.login_started_at_ns,
99        claims.login_deadline_ns,
100        claims.issued_at_ns,
101        claims.admission_expires_at_ns,
102    ] {
103        out(&time.to_be_bytes());
104    }
105    out(&claims.nonce);
106    grants.encode(&mut out)?;
107    if length > MAX_CLAIMS_BYTES {
108        return Err(PortableEncodingError::TooLarge);
109    }
110    Ok(())
111}
112
113/// Decode bounded canonical claims. Lengths/counts are admitted before allocation;
114/// unknown schema/mechanism, trailing bytes and noncanonical grants are rejected.
115/// This is deliberately not a deserializer for the previous token domain.
116pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, PortableEncodingError> {
117    if bytes.len() > MAX_CLAIMS_BYTES {
118        return Err(PortableEncodingError::TooLarge);
119    }
120    let mut input = Reader(bytes);
121    if input.take(DOMAIN.len())? != DOMAIN || input.array::<2>()? != SCHEMA.to_be_bytes() {
122        return Err(PortableEncodingError::WrongDomain);
123    }
124    let mechanism = match input.array::<1>()? {
125        [0] => PortableMechanism::Certified,
126        [1] => PortableMechanism::Ed25519,
127        _ => return Err(PortableEncodingError::WrongDomain),
128    };
129    let audience = AudienceId {
130        canonical_network_id: CanonicalId::from_bytes(input.array()?),
131        fleet_id: CanonicalId::from_bytes(input.array()?),
132    };
133    let issuer = input.principal()?;
134    let key_binding_id = input.array()?;
135    let browser_public_key = input.array()?;
136    let account_subject = input.principal()?;
137    let login_started_at_ns = u64::from_be_bytes(input.array()?);
138    let login_deadline_ns = u64::from_be_bytes(input.array()?);
139    let issued_at_ns = u64::from_be_bytes(input.array()?);
140    let admission_expires_at_ns = u64::from_be_bytes(input.array()?);
141    let nonce = input.array()?;
142    let count = input.count(MAX_GRANTS)?;
143    let mut grants = Vec::with_capacity(count);
144    for _ in 0..count {
145        let target = input
146            .label()?
147            .parse()
148            .map_err(|_| PortableEncodingError::InvalidShape)?;
149        let count = input.count(MAX_SCOPES_PER_GRANT)?;
150        let mut scopes = Vec::with_capacity(count);
151        for _ in 0..count {
152            scopes.push(
153                input
154                    .label()?
155                    .parse()
156                    .map_err(|_| PortableEncodingError::InvalidShape)?,
157            );
158        }
159        grants.push(DelegatedRoleGrant { target, scopes });
160    }
161    if !input.0.is_empty() {
162        return Err(PortableEncodingError::TrailingBytes);
163    }
164    let claims = PortableClaims {
165        mechanism,
166        audience,
167        issuer,
168        key_binding_id,
169        browser_public_key,
170        account_subject,
171        login_started_at_ns,
172        login_deadline_ns,
173        issued_at_ns,
174        admission_expires_at_ns,
175        nonce,
176        grants,
177    };
178    validate_shape(&claims)?;
179    Ok(claims)
180}
181
182/// SHA-256 of the exact canonical signed blob, for signing and replay identity.
183/// The digest authenticates nothing by itself; signature bytes are not included.
184pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], PortableEncodingError> {
185    let mut hash = Sha256::new();
186    encode_claims_into(claims, &mut |bytes| hash.update(bytes))?;
187    Ok(hash.finalize().into())
188}
189
190/// Derive the IC sender for a directly authenticated Ed25519 browser key.
191/// Hosts must compare this with the actual ingress caller, not a client field.
192/// This does not validate curve membership or possession of the key.
193pub fn browser_principal(public_key: &[u8; 32]) -> Principal {
194    // RFC 8410 Ed25519 SubjectPublicKeyInfo: SEQUENCE(algorithm OID, BIT STRING).
195    let mut der = [0; 44];
196    der[..12].copy_from_slice(&[
197        0x30, 0x2a, 0x30, 0x05, 0x06, 0x03, 0x2b, 0x65, 0x70, 0x03, 0x21, 0,
198    ]);
199    der[12..].copy_from_slice(public_key);
200    Principal::self_authenticating(der)
201}
202
203// A login caller must have the complete self-authenticating principal shape.
204// This checks neither ingress provenance nor possession of the browser key.
205pub(crate) fn is_login_caller(caller: Principal) -> bool {
206    let bytes = caller.as_slice();
207    bytes.len() == 29 && bytes.last() == Some(&2)
208}
209
210fn validate_shape(claims: &PortableClaims) -> Result<CheckedGrants<'_>, PortableEncodingError> {
211    if claims.account_subject == Principal::anonymous() {
212        return Err(PortableEncodingError::AnonymousSubject);
213    }
214    Ok(CheckedGrants::bounded(
215        &claims.grants,
216        MAX_GRANTS,
217        MAX_SCOPES_PER_GRANT,
218    )?)
219}
220
221struct Reader<'a>(&'a [u8]);
222
223impl<'a> Reader<'a> {
224    fn take(&mut self, len: usize) -> Result<&'a [u8], PortableEncodingError> {
225        let (head, tail) = self
226            .0
227            .split_at_checked(len)
228            .ok_or(PortableEncodingError::Truncated)?;
229        self.0 = tail;
230        Ok(head)
231    }
232
233    fn array<const N: usize>(&mut self) -> Result<[u8; N], PortableEncodingError> {
234        self.take(N)?
235            .try_into()
236            .map_err(|_| PortableEncodingError::Truncated)
237    }
238
239    fn length(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
240        let len = u32::from_be_bytes(self.array()?);
241        let len = usize::try_from(len).map_err(|_| PortableEncodingError::InvalidShape)?;
242        if len > max {
243            return Err(PortableEncodingError::InvalidShape);
244        }
245        Ok(len)
246    }
247
248    fn count(&mut self, max: usize) -> Result<usize, PortableEncodingError> {
249        let count = self.length(max)?;
250        if count == 0 {
251            return Err(PortableEncodingError::InvalidShape);
252        }
253        Ok(count)
254    }
255
256    fn principal(&mut self) -> Result<Principal, PortableEncodingError> {
257        let len = self.length(29)?;
258        Ok(Principal::from_slice(self.take(len)?))
259    }
260
261    fn label(&mut self) -> Result<&'a str, PortableEncodingError> {
262        let len = self.count(MAX_LABEL_BYTES)?;
263        std::str::from_utf8(self.take(len)?).map_err(|_| PortableEncodingError::InvalidShape)
264    }
265}
266
267#[cfg(test)]
268mod tests;