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