1use 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 EXTENDED_SCHEMA: u16 = 3;
15const MAX_ROLES: usize = 16;
16const MAX_SCOPES_PER_ROLE: usize = 32;
17const MAX_SCOPE_ENTRIES: usize = 32;
18const MAX_LABEL_BYTES: usize = 64;
19const MAX_GRANT_BYTES: usize = 4096;
20
21pub const MAX_CLAIMS_BYTES: usize = 65_536;
23
24const _: () = assert!(
27 4 + MAX_ROLES * (8 + MAX_LABEL_BYTES) + MAX_SCOPE_ENTRIES * (4 + MAX_LABEL_BYTES)
28 <= MAX_GRANT_BYTES
29);
30const _: () = assert!(
32 282 + 4 + ic_auth_protocol_types::MAX_TOKEN_EXT_BYTES + MAX_GRANT_BYTES <= MAX_CLAIMS_BYTES
33);
34
35#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub enum ClaimsError {
43 TooLarge,
45 Truncated,
47 WrongDomain,
49 TrailingBytes,
51 InvalidShape,
53 AnonymousSubject,
55 NonCanonicalRoles,
57 NonCanonicalScopes,
59 InvalidGrantCount {
61 found: usize,
63 },
64 InvalidScopeCount {
66 found: usize,
68 },
69 TooManyScopeEntries {
71 found: usize,
73 max: usize,
75 },
76}
77
78impl fmt::Display for ClaimsError {
79 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
80 let message = match self {
81 Self::TooLarge => "claims exceed their byte bound",
82 Self::Truncated => "truncated claims",
83 Self::WrongDomain => "unsupported claims domain, schema or mechanism",
84 Self::TrailingBytes => "trailing claims bytes",
85 Self::InvalidShape => "invalid claims structure",
86 Self::AnonymousSubject => "anonymous account subject",
87 Self::NonCanonicalRoles => "roles must be strictly ordered and unique",
88 Self::NonCanonicalScopes => "scopes must be strictly ordered and unique",
89 Self::InvalidGrantCount { found } => {
90 return write!(f, "grant count {found} is outside 1..=16");
91 }
92 Self::InvalidScopeCount { found } => {
93 return write!(f, "scope count {found} is outside 1..=32");
94 }
95 Self::TooManyScopeEntries { found, max } => {
96 return write!(f, "credential has {found} scope entries; maximum is {max}");
97 }
98 };
99 f.write_str(message)
100 }
101}
102
103impl Error for ClaimsError {}
104
105fn check_entries(found: usize) -> Result<(), ClaimsError> {
106 if found > MAX_SCOPE_ENTRIES {
107 return Err(ClaimsError::TooManyScopeEntries {
108 found,
109 max: MAX_SCOPE_ENTRIES,
110 });
111 }
112 Ok(())
113}
114
115fn validate(claims: &PortableClaims) -> Result<(), ClaimsError> {
116 if claims
117 .ext
118 .as_ref()
119 .is_some_and(|ext| ext.len() > ic_auth_protocol_types::MAX_TOKEN_EXT_BYTES)
120 {
121 return Err(ClaimsError::TooLarge);
122 }
123 if claims.device_slot > 7 || claims.device_generation == 0 {
124 return Err(ClaimsError::InvalidShape);
125 }
126 if claims.account_subject == Principal::anonymous() {
127 return Err(ClaimsError::AnonymousSubject);
128 }
129 validate_grants(&claims.grants)?;
130 check_entries(claims.grants.iter().map(|grant| grant.scopes.len()).sum())
131}
132
133pub(crate) fn validate_grants(grants: &[DelegatedRoleGrant]) -> Result<(), ClaimsError> {
136 if !(1..=MAX_ROLES).contains(&grants.len()) {
137 return Err(ClaimsError::InvalidGrantCount {
138 found: grants.len(),
139 });
140 }
141 for (index, grant) in grants.iter().enumerate() {
142 if index > 0 && grants[index - 1].target >= grant.target {
143 return Err(ClaimsError::NonCanonicalRoles);
144 }
145 if !(1..=MAX_SCOPES_PER_ROLE).contains(&grant.scopes.len()) {
146 return Err(ClaimsError::InvalidScopeCount {
147 found: grant.scopes.len(),
148 });
149 }
150 if grant.scopes.windows(2).any(|pair| pair[0] >= pair[1]) {
151 return Err(ClaimsError::NonCanonicalScopes);
152 }
153 }
154 Ok(())
155}
156
157pub fn encode_claims(claims: &PortableClaims) -> Result<Vec<u8>, ClaimsError> {
162 validate(claims)?;
163 let mut output = Vec::new();
164 write_fields(claims, |bytes| output.extend_from_slice(bytes));
165 Ok(output)
166}
167
168pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], ClaimsError> {
173 validate(claims)?;
174 let mut digest = Sha256::new();
175 write_fields(claims, |bytes| digest.update(bytes));
176 Ok(digest.finalize().into())
177}
178
179fn write_fields(claims: &PortableClaims, mut emit: impl FnMut(&[u8])) {
182 emit(DOMAIN);
183 let schema = if claims.ext.is_some() {
184 EXTENDED_SCHEMA
185 } else {
186 SCHEMA
187 };
188 emit(&schema.to_be_bytes());
189 emit(&[match claims.mechanism {
190 PortableMechanism::Certified => 0,
191 PortableMechanism::Ed25519 => 1,
192 }]);
193 emit(claims.audience.canonical_network_id.as_bytes());
194 emit(claims.audience.fleet_id.as_bytes());
195 emit(&(u32::from(claims.issuer.len())).to_be_bytes());
196 emit(claims.issuer.as_slice());
197 emit(&claims.key_binding_id);
198 emit(&claims.browser_public_key);
199 emit(&(u32::from(claims.account_subject.len())).to_be_bytes());
200 emit(claims.account_subject.as_slice());
201 if let Some(ext) = &claims.ext {
202 emit(&(ext.len() as u32).to_be_bytes());
203 emit(ext);
204 }
205 emit(&[claims.device_slot]);
206 for value in [
207 claims.device_generation,
208 claims.login_started_at_ns,
209 claims.login_deadline_ns,
210 claims.issued_at_ns,
211 claims.admission_expires_at_ns,
212 ] {
213 emit(&value.to_be_bytes());
214 }
215 emit(&claims.nonce);
216 write_grants(&claims.grants, &mut emit);
217}
218
219pub(crate) fn write_grants(grants: &[DelegatedRoleGrant], emit: &mut dyn FnMut(&[u8])) {
222 emit(&(grants.len() as u32).to_be_bytes());
223 for grant in grants {
224 emit(&(grant.target.as_str().len() as u32).to_be_bytes());
225 emit(grant.target.as_str().as_bytes());
226 emit(&(grant.scopes.len() as u32).to_be_bytes());
227 for scope in &grant.scopes {
228 emit(&(scope.as_str().len() as u32).to_be_bytes());
229 emit(scope.as_str().as_bytes());
230 }
231 }
232}
233
234pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, ClaimsError> {
239 if bytes.len() > MAX_CLAIMS_BYTES {
240 return Err(ClaimsError::TooLarge);
241 }
242 let mut input = Input { remaining: bytes };
243 if input.take(DOMAIN.len())? != DOMAIN {
244 return Err(ClaimsError::WrongDomain);
245 }
246 let schema = u16::from_be_bytes(input.fixed()?);
247 if !matches!(schema, SCHEMA | EXTENDED_SCHEMA) {
248 return Err(ClaimsError::WrongDomain);
249 }
250 let mechanism = match input.fixed()? {
251 [0] => PortableMechanism::Certified,
252 [1] => PortableMechanism::Ed25519,
253 _ => return Err(ClaimsError::WrongDomain),
254 };
255 let audience = AudienceId {
256 canonical_network_id: CanonicalId::from_bytes(input.fixed()?),
257 fleet_id: CanonicalId::from_bytes(input.fixed()?),
258 };
259 let issuer = input.principal()?;
260 let key_binding_id = input.fixed()?;
261 let browser_public_key = input.fixed()?;
262 let account_subject = input.principal()?;
263 let ext = if schema == EXTENDED_SCHEMA {
264 let len = input.size(0, ic_auth_protocol_types::MAX_TOKEN_EXT_BYTES)?;
265 Some(input.take(len)?.to_vec())
266 } else {
267 None
268 };
269 let [device_slot] = input.fixed()?;
270 let device_generation = u64::from_be_bytes(input.fixed()?);
271 let login_started_at_ns = u64::from_be_bytes(input.fixed()?);
272 let login_deadline_ns = u64::from_be_bytes(input.fixed()?);
273 let issued_at_ns = u64::from_be_bytes(input.fixed()?);
274 let admission_expires_at_ns = u64::from_be_bytes(input.fixed()?);
275 let nonce = input.fixed()?;
276 if input.remaining.len() > MAX_GRANT_BYTES {
278 return Err(ClaimsError::TooLarge);
279 }
280 let roles = input.size(1, MAX_ROLES)?;
281 let mut grants = Vec::with_capacity(roles);
282 let mut entries = 0;
283 for _ in 0..roles {
284 let target = input
285 .label()?
286 .parse()
287 .map_err(|_| ClaimsError::InvalidShape)?;
288 let count = input.size(1, MAX_SCOPES_PER_ROLE)?;
289 entries += count;
290 check_entries(entries)?;
291 let mut scopes = Vec::with_capacity(count);
292 for _ in 0..count {
293 scopes.push(
294 input
295 .label()?
296 .parse()
297 .map_err(|_| ClaimsError::InvalidShape)?,
298 );
299 }
300 grants.push(DelegatedRoleGrant { target, scopes });
301 }
302 if !input.remaining.is_empty() {
303 return Err(ClaimsError::TrailingBytes);
304 }
305 let claims = PortableClaims {
306 mechanism,
307 audience,
308 issuer,
309 key_binding_id,
310 browser_public_key,
311 account_subject,
312 ext,
313 device_slot,
314 device_generation,
315 login_started_at_ns,
316 login_deadline_ns,
317 issued_at_ns,
318 admission_expires_at_ns,
319 nonce,
320 grants,
321 };
322 validate(&claims)?;
323 Ok(claims)
324}
325
326struct Input<'a> {
336 remaining: &'a [u8],
337}
338
339impl<'a> Input<'a> {
340 fn take(&mut self, length: usize) -> Result<&'a [u8], ClaimsError> {
341 let head = self.remaining.get(..length).ok_or(ClaimsError::Truncated)?;
342 self.remaining = &self.remaining[length..];
343 Ok(head)
344 }
345
346 fn fixed<const N: usize>(&mut self) -> Result<[u8; N], ClaimsError> {
347 self.take(N)?.try_into().map_err(|_| ClaimsError::Truncated)
348 }
349
350 fn size(&mut self, minimum: usize, maximum: usize) -> Result<usize, ClaimsError> {
351 let size = usize::try_from(u32::from_be_bytes(self.fixed()?))
352 .map_err(|_| ClaimsError::InvalidShape)?;
353 if !(minimum..=maximum).contains(&size) {
354 return Err(ClaimsError::InvalidShape);
355 }
356 Ok(size)
357 }
358
359 fn principal(&mut self) -> Result<Principal, ClaimsError> {
360 let size = self.size(0, Principal::MAX_LENGTH_IN_BYTES)?;
361 Principal::try_from_slice(self.take(size)?).map_err(|_| ClaimsError::InvalidShape)
362 }
363
364 fn label(&mut self) -> Result<&'a str, ClaimsError> {
365 let size = self.size(1, MAX_LABEL_BYTES)?;
366 std::str::from_utf8(self.take(size)?).map_err(|_| ClaimsError::InvalidShape)
367 }
368}