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 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
20pub const MAX_CLAIMS_BYTES: usize = 65_536;
22
23const _: () = assert!(
26 4 + MAX_ROLES * (8 + MAX_LABEL_BYTES) + MAX_SCOPE_ENTRIES * (4 + MAX_LABEL_BYTES)
27 <= MAX_GRANT_BYTES
28);
29const _: () = assert!(282 + MAX_GRANT_BYTES <= MAX_CLAIMS_BYTES);
31
32#[derive(Clone, Copy, Debug, Eq, PartialEq)]
39pub enum ClaimsError {
40 TooLarge,
42 Truncated,
44 WrongDomain,
46 TrailingBytes,
48 InvalidShape,
50 AnonymousSubject,
52 NonCanonicalRoles,
54 NonCanonicalScopes,
56 InvalidGrantCount {
58 found: usize,
60 },
61 InvalidScopeCount {
63 found: usize,
65 },
66 TooManyScopeEntries {
68 found: usize,
70 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
123pub(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
147pub 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
158pub 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
169fn 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
200pub(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
215pub 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 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
296struct 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}