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)]
34pub enum ClaimsError {
35 TooLarge,
37 Truncated,
39 WrongDomain,
41 TrailingBytes,
43 InvalidShape,
45 AnonymousSubject,
47 NonCanonicalRoles,
49 NonCanonicalScopes,
51 InvalidGrantCount {
53 found: usize,
55 },
56 InvalidScopeCount {
58 found: usize,
60 },
61 TooManyScopeEntries {
63 found: usize,
65 max: usize,
67 },
68}
69
70impl fmt::Display for ClaimsError {
71 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
72 let message = match self {
73 Self::TooLarge => "claims exceed their byte bound",
74 Self::Truncated => "truncated claims",
75 Self::WrongDomain => "unsupported claims domain, schema or mechanism",
76 Self::TrailingBytes => "trailing claims bytes",
77 Self::InvalidShape => "invalid claims structure",
78 Self::AnonymousSubject => "anonymous account subject",
79 Self::NonCanonicalRoles => "roles must be strictly ordered and unique",
80 Self::NonCanonicalScopes => "scopes must be strictly ordered and unique",
81 Self::InvalidGrantCount { found } => {
82 return write!(f, "grant count {found} is outside 1..=16");
83 }
84 Self::InvalidScopeCount { found } => {
85 return write!(f, "scope count {found} is outside 1..=32");
86 }
87 Self::TooManyScopeEntries { found, max } => {
88 return write!(f, "credential has {found} scope entries; maximum is {max}");
89 }
90 };
91 f.write_str(message)
92 }
93}
94
95impl Error for ClaimsError {}
96
97fn check_entries(found: usize) -> Result<(), ClaimsError> {
98 if found > MAX_SCOPE_ENTRIES {
99 return Err(ClaimsError::TooManyScopeEntries {
100 found,
101 max: MAX_SCOPE_ENTRIES,
102 });
103 }
104 Ok(())
105}
106
107fn validate(claims: &PortableClaims) -> Result<(), ClaimsError> {
108 if claims.device_slot > 7 || claims.device_generation == 0 {
109 return Err(ClaimsError::InvalidShape);
110 }
111 if claims.account_subject == Principal::anonymous() {
112 return Err(ClaimsError::AnonymousSubject);
113 }
114 validate_grants(&claims.grants)?;
115 check_entries(claims.grants.iter().map(|grant| grant.scopes.len()).sum())
116}
117
118pub(crate) fn validate_grants(grants: &[DelegatedRoleGrant]) -> Result<(), ClaimsError> {
121 if !(1..=MAX_ROLES).contains(&grants.len()) {
122 return Err(ClaimsError::InvalidGrantCount {
123 found: grants.len(),
124 });
125 }
126 for (index, grant) in grants.iter().enumerate() {
127 if index > 0 && grants[index - 1].target >= grant.target {
128 return Err(ClaimsError::NonCanonicalRoles);
129 }
130 if !(1..=MAX_SCOPES_PER_ROLE).contains(&grant.scopes.len()) {
131 return Err(ClaimsError::InvalidScopeCount {
132 found: grant.scopes.len(),
133 });
134 }
135 if grant.scopes.windows(2).any(|pair| pair[0] >= pair[1]) {
136 return Err(ClaimsError::NonCanonicalScopes);
137 }
138 }
139 Ok(())
140}
141
142pub fn encode_claims(claims: &PortableClaims) -> Result<Vec<u8>, ClaimsError> {
147 validate(claims)?;
148 let mut output = Vec::new();
149 write_fields(claims, |bytes| output.extend_from_slice(bytes));
150 Ok(output)
151}
152
153pub fn claims_hash(claims: &PortableClaims) -> Result<[u8; 32], ClaimsError> {
158 validate(claims)?;
159 let mut digest = Sha256::new();
160 write_fields(claims, |bytes| digest.update(bytes));
161 Ok(digest.finalize().into())
162}
163
164fn write_fields(claims: &PortableClaims, mut emit: impl FnMut(&[u8])) {
167 emit(DOMAIN);
168 emit(&SCHEMA.to_be_bytes());
169 emit(&[match claims.mechanism {
170 PortableMechanism::Certified => 0,
171 PortableMechanism::Ed25519 => 1,
172 }]);
173 emit(claims.audience.canonical_network_id.as_bytes());
174 emit(claims.audience.fleet_id.as_bytes());
175 emit(&(u32::from(claims.issuer.len())).to_be_bytes());
176 emit(claims.issuer.as_slice());
177 emit(&claims.key_binding_id);
178 emit(&claims.browser_public_key);
179 emit(&(u32::from(claims.account_subject.len())).to_be_bytes());
180 emit(claims.account_subject.as_slice());
181 emit(&[claims.device_slot]);
182 for value in [
183 claims.device_generation,
184 claims.login_started_at_ns,
185 claims.login_deadline_ns,
186 claims.issued_at_ns,
187 claims.admission_expires_at_ns,
188 ] {
189 emit(&value.to_be_bytes());
190 }
191 emit(&claims.nonce);
192 write_grants(&claims.grants, &mut emit);
193}
194
195pub(crate) fn write_grants(grants: &[DelegatedRoleGrant], emit: &mut dyn FnMut(&[u8])) {
198 emit(&(grants.len() as u32).to_be_bytes());
199 for grant in grants {
200 emit(&(grant.target.as_str().len() as u32).to_be_bytes());
201 emit(grant.target.as_str().as_bytes());
202 emit(&(grant.scopes.len() as u32).to_be_bytes());
203 for scope in &grant.scopes {
204 emit(&(scope.as_str().len() as u32).to_be_bytes());
205 emit(scope.as_str().as_bytes());
206 }
207 }
208}
209
210pub fn decode_claims(bytes: &[u8]) -> Result<PortableClaims, ClaimsError> {
215 if bytes.len() > MAX_CLAIMS_BYTES {
216 return Err(ClaimsError::TooLarge);
217 }
218 let mut input = Input { remaining: bytes };
219 if input.take(DOMAIN.len())? != DOMAIN || u16::from_be_bytes(input.fixed()?) != SCHEMA {
220 return Err(ClaimsError::WrongDomain);
221 }
222 let mechanism = match input.fixed()? {
223 [0] => PortableMechanism::Certified,
224 [1] => PortableMechanism::Ed25519,
225 _ => return Err(ClaimsError::WrongDomain),
226 };
227 let audience = AudienceId {
228 canonical_network_id: CanonicalId::from_bytes(input.fixed()?),
229 fleet_id: CanonicalId::from_bytes(input.fixed()?),
230 };
231 let issuer = input.principal()?;
232 let key_binding_id = input.fixed()?;
233 let browser_public_key = input.fixed()?;
234 let account_subject = input.principal()?;
235 let [device_slot] = input.fixed()?;
236 let device_generation = u64::from_be_bytes(input.fixed()?);
237 let login_started_at_ns = u64::from_be_bytes(input.fixed()?);
238 let login_deadline_ns = u64::from_be_bytes(input.fixed()?);
239 let issued_at_ns = u64::from_be_bytes(input.fixed()?);
240 let admission_expires_at_ns = u64::from_be_bytes(input.fixed()?);
241 let nonce = input.fixed()?;
242 if input.remaining.len() > MAX_GRANT_BYTES {
244 return Err(ClaimsError::TooLarge);
245 }
246 let roles = input.size(1, MAX_ROLES)?;
247 let mut grants = Vec::with_capacity(roles);
248 let mut entries = 0;
249 for _ in 0..roles {
250 let target = input
251 .label()?
252 .parse()
253 .map_err(|_| ClaimsError::InvalidShape)?;
254 let count = input.size(1, MAX_SCOPES_PER_ROLE)?;
255 entries += count;
256 check_entries(entries)?;
257 let mut scopes = Vec::with_capacity(count);
258 for _ in 0..count {
259 scopes.push(
260 input
261 .label()?
262 .parse()
263 .map_err(|_| ClaimsError::InvalidShape)?,
264 );
265 }
266 grants.push(DelegatedRoleGrant { target, scopes });
267 }
268 if !input.remaining.is_empty() {
269 return Err(ClaimsError::TrailingBytes);
270 }
271 let claims = PortableClaims {
272 mechanism,
273 audience,
274 issuer,
275 key_binding_id,
276 browser_public_key,
277 account_subject,
278 device_slot,
279 device_generation,
280 login_started_at_ns,
281 login_deadline_ns,
282 issued_at_ns,
283 admission_expires_at_ns,
284 nonce,
285 grants,
286 };
287 validate(&claims)?;
288 Ok(claims)
289}
290
291struct Input<'a> {
294 remaining: &'a [u8],
295}
296
297impl<'a> Input<'a> {
298 fn take(&mut self, length: usize) -> Result<&'a [u8], ClaimsError> {
299 let head = self.remaining.get(..length).ok_or(ClaimsError::Truncated)?;
300 self.remaining = &self.remaining[length..];
301 Ok(head)
302 }
303
304 fn fixed<const N: usize>(&mut self) -> Result<[u8; N], ClaimsError> {
305 self.take(N)?.try_into().map_err(|_| ClaimsError::Truncated)
306 }
307
308 fn size(&mut self, minimum: usize, maximum: usize) -> Result<usize, ClaimsError> {
309 let size = usize::try_from(u32::from_be_bytes(self.fixed()?))
310 .map_err(|_| ClaimsError::InvalidShape)?;
311 if !(minimum..=maximum).contains(&size) {
312 return Err(ClaimsError::InvalidShape);
313 }
314 Ok(size)
315 }
316
317 fn principal(&mut self) -> Result<Principal, ClaimsError> {
318 let size = self.size(0, Principal::MAX_LENGTH_IN_BYTES)?;
319 Principal::try_from_slice(self.take(size)?).map_err(|_| ClaimsError::InvalidShape)
320 }
321
322 fn label(&mut self) -> Result<&'a str, ClaimsError> {
323 let size = self.size(1, MAX_LABEL_BYTES)?;
324 std::str::from_utf8(self.take(size)?).map_err(|_| ClaimsError::InvalidShape)
325 }
326}