1use crate::generated::font_bundle_manifest::{FontBundleEntry, FontBundleManifestA0};
2use crate::generated::font_resolution_request::FontResolutionRequestA0;
3use crate::{ValidationError, validation_error};
4use sha2::{Digest, Sha256};
5use std::collections::{HashMap, HashSet};
6
7#[derive(Clone, Copy, Debug, Eq, PartialEq)]
9pub struct FontBundleLimits {
10 pub max_fonts: usize,
11 pub max_font_bytes: usize,
12 pub max_total_font_bytes: usize,
13 pub max_aliases_per_font: usize,
14 pub max_variations_per_font: usize,
15 pub max_metadata_string_bytes: usize,
16}
17
18impl Default for FontBundleLimits {
19 fn default() -> Self {
20 Self {
21 max_fonts: 4_096,
22 max_font_bytes: 256 * 1024 * 1024,
23 max_total_font_bytes: 1024 * 1024 * 1024,
24 max_aliases_per_font: 4_096,
25 max_variations_per_font: 4_096,
26 max_metadata_string_bytes: 64 * 1024 * 1024,
27 }
28 }
29}
30
31#[derive(Clone, Copy, Debug, Eq, PartialEq)]
33pub struct FontResolutionLimits {
34 pub max_request_aliases: usize,
35 pub max_request_string_bytes: usize,
36}
37
38impl Default for FontResolutionLimits {
39 fn default() -> Self {
40 Self {
41 max_request_aliases: 4_096,
42 max_request_string_bytes: 16 * 1024 * 1024,
43 }
44 }
45}
46
47#[derive(Clone, Copy, Debug, Eq, PartialEq)]
48enum AliasTarget {
49 Unique(usize),
50 Ambiguous,
51}
52
53#[derive(Debug)]
55pub struct ValidatedFontBundle<'a> {
56 manifest: &'a FontBundleManifestA0,
57 id_index: HashMap<&'a str, usize>,
58 alias_index: HashMap<&'a str, AliasTarget>,
59}
60
61pub fn validate_font_bundle_contract<'a>(
63 manifest: &'a FontBundleManifestA0,
64 buffers: &[&[u8]],
65 limits: FontBundleLimits,
66) -> Result<ValidatedFontBundle<'a>, ValidationError> {
67 validate_identity(manifest)?;
68 if manifest.fonts.len() > limits.max_fonts {
69 return Err(error(
70 "resource_limit",
71 "$.fonts",
72 "font count exceeds its limit",
73 ));
74 }
75 if manifest.fonts.len() != buffers.len() {
76 return Err(error(
77 "buffer_count_mismatch",
78 "$.fonts",
79 "every supplied buffer must be referenced exactly once",
80 ));
81 }
82 let mut ids = HashSet::with_capacity(manifest.fonts.len());
83 let mut slots = HashSet::with_capacity(manifest.fonts.len());
84 let mut total_bytes = 0usize;
85 let mut metadata_string_bytes = 0usize;
86 for (index, font) in manifest.fonts.iter().enumerate() {
87 validate_font_metadata(font, index, limits, &mut ids, &mut slots)?;
88 metadata_string_bytes = metadata_string_bytes
89 .checked_add(font_metadata_string_bytes(font)?)
90 .ok_or_else(|| error("resource_limit", "$.fonts", "font metadata bytes overflow"))?;
91 if metadata_string_bytes > limits.max_metadata_string_bytes {
92 return Err(error(
93 "resource_limit",
94 "$.fonts",
95 "font metadata string bytes exceed their limit",
96 ));
97 }
98 let slot = usize::try_from(font.slot).map_err(|_| {
99 error(
100 "invalid_slot",
101 format!("$.fonts[{index}].slot"),
102 "font slot is not platform-sized",
103 )
104 })?;
105 let buffer = buffers.get(slot).ok_or_else(|| {
106 error(
107 "invalid_slot",
108 format!("$.fonts[{index}].slot"),
109 "font slot is out of range",
110 )
111 })?;
112 if buffer.len() > limits.max_font_bytes {
113 return Err(error(
114 "resource_limit",
115 format!("$.fonts[{index}].slot"),
116 "font buffer exceeds its byte limit",
117 ));
118 }
119 total_bytes = total_bytes.checked_add(buffer.len()).ok_or_else(|| {
120 error(
121 "resource_limit",
122 "$.fonts",
123 "total font buffer bytes overflow",
124 )
125 })?;
126 if total_bytes > limits.max_total_font_bytes {
127 return Err(error(
128 "resource_limit",
129 "$.fonts",
130 "total font buffer bytes exceed their limit",
131 ));
132 }
133 }
134 for (index, font) in manifest.fonts.iter().enumerate() {
135 let buffer = buffers[font.slot as usize];
136 if !sha256_matches(buffer, &font.sha256.0) {
137 return Err(error(
138 "hash_mismatch",
139 format!("$.fonts[{index}].sha256"),
140 "font bytes do not match the declared SHA-256",
141 ));
142 }
143 }
144 Ok(ValidatedFontBundle {
145 manifest,
146 id_index: manifest
147 .fonts
148 .iter()
149 .enumerate()
150 .map(|(index, font)| (font.id.as_str(), index))
151 .collect(),
152 alias_index: build_alias_index(manifest),
153 })
154}
155
156pub fn resolve_font_selection_contract<'a>(
158 bundle: &'a ValidatedFontBundle<'a>,
159 request: &FontResolutionRequestA0,
160 limits: FontResolutionLimits,
161) -> Result<&'a FontBundleEntry, ValidationError> {
162 if request.schema != "kicad_monkey.font_resolution_request.a0"
163 || request.type_ != "kicad_monkey.font_resolution_request"
164 || request.version != "a0"
165 {
166 return Err(error(
167 "unsupported_contract",
168 "$",
169 "unsupported font resolution contract identity",
170 ));
171 }
172 validate_resolution_request(request, limits)?;
173 if let Some(id) = request.selection.font_id.as_deref() {
174 let index = bundle.id_index.get(id).ok_or_else(|| {
175 error(
176 "missing_font",
177 "$.selection.font_id",
178 "font ID is not present",
179 )
180 })?;
181 return Ok(&bundle.manifest.fonts[*index]);
182 }
183 let mut matched_index = None;
184 for requested in &request.selection.aliases {
185 match bundle.alias_index.get(requested.as_str()) {
186 Some(AliasTarget::Ambiguous) => {
187 return Err(error(
188 "ambiguous_font",
189 "$.selection.aliases",
190 "font aliases resolve to more than one bundle entry",
191 ));
192 }
193 Some(AliasTarget::Unique(index)) => match matched_index {
194 Some(previous) if previous != *index => {
195 return Err(error(
196 "ambiguous_font",
197 "$.selection.aliases",
198 "font aliases resolve to more than one bundle entry",
199 ));
200 }
201 None => matched_index = Some(*index),
202 _ => {}
203 },
204 None => {}
205 }
206 }
207 matched_index
208 .map(|index| &bundle.manifest.fonts[index])
209 .ok_or_else(|| error("missing_font", "$.selection", "font selection has no match"))
210}
211
212fn validate_resolution_request(
213 request: &FontResolutionRequestA0,
214 limits: FontResolutionLimits,
215) -> Result<(), ValidationError> {
216 if request.selection.aliases.len() > limits.max_request_aliases {
217 return Err(error(
218 "resource_limit",
219 "$.selection.aliases",
220 "font request alias count exceeds its limit",
221 ));
222 }
223 let mut strings = request.selection.aliases.iter().map(String::as_str);
224 let request_bytes = strings
225 .try_fold(
226 request.selection.font_id.as_deref().map_or(0, str::len),
227 |total, value| total.checked_add(value.len()),
228 )
229 .ok_or_else(|| {
230 error(
231 "resource_limit",
232 "$.selection",
233 "font request bytes overflow",
234 )
235 })?;
236 if request_bytes > limits.max_request_string_bytes {
237 return Err(error(
238 "resource_limit",
239 "$.selection",
240 "font request string bytes exceed their limit",
241 ));
242 }
243 if request.selection.font_id.as_deref() == Some("") {
244 return Err(error(
245 "invalid_selection",
246 "$.selection.font_id",
247 "explicit font ID must be nonempty",
248 ));
249 }
250 let mut aliases = HashSet::with_capacity(request.selection.aliases.len());
251 if request
252 .selection
253 .aliases
254 .iter()
255 .any(|alias| alias.is_empty() || !aliases.insert(alias))
256 {
257 return Err(error(
258 "invalid_selection",
259 "$.selection.aliases",
260 "request aliases must be nonempty and unique",
261 ));
262 }
263 Ok(())
264}
265
266fn build_alias_index(manifest: &FontBundleManifestA0) -> HashMap<&str, AliasTarget> {
267 let mut index = HashMap::new();
268 for (font_index, font) in manifest.fonts.iter().enumerate() {
269 for alias in &font.aliases {
270 index
271 .entry(alias.as_str())
272 .and_modify(|target| {
273 if *target != AliasTarget::Unique(font_index) {
274 *target = AliasTarget::Ambiguous;
275 }
276 })
277 .or_insert(AliasTarget::Unique(font_index));
278 }
279 }
280 index
281}
282
283fn font_metadata_string_bytes(font: &FontBundleEntry) -> Result<usize, ValidationError> {
284 let fixed = [
285 Some(font.id.as_str()),
286 Some(font.sha256.0.as_str()),
287 font.family.as_deref(),
288 font.style.as_deref(),
289 font.postscript_name.as_deref(),
290 ];
291 fixed
292 .into_iter()
293 .flatten()
294 .chain(font.aliases.iter().map(String::as_str))
295 .chain(font.variations.iter().map(|value| value.axis.0.as_str()))
296 .try_fold(0usize, |total, value| total.checked_add(value.len()))
297 .ok_or_else(|| error("resource_limit", "$.fonts", "font metadata bytes overflow"))
298}
299
300fn validate_identity(manifest: &FontBundleManifestA0) -> Result<(), ValidationError> {
301 if manifest.schema == "kicad_monkey.font_bundle.a0"
302 && manifest.type_ == "kicad_monkey.font_bundle"
303 && manifest.version == "a0"
304 {
305 Ok(())
306 } else {
307 Err(error(
308 "unsupported_contract",
309 "$",
310 "unsupported font bundle contract identity",
311 ))
312 }
313}
314
315fn validate_font_metadata<'a>(
316 font: &'a FontBundleEntry,
317 index: usize,
318 limits: FontBundleLimits,
319 ids: &mut HashSet<&'a str>,
320 slots: &mut HashSet<u32>,
321) -> Result<(), ValidationError> {
322 if font.id.is_empty() || !ids.insert(&font.id) {
323 return Err(error(
324 "duplicate_font_id",
325 format!("$.fonts[{index}].id"),
326 "font IDs must be nonempty and unique",
327 ));
328 }
329 if !slots.insert(font.slot) {
330 return Err(error(
331 "duplicate_font_slot",
332 format!("$.fonts[{index}].slot"),
333 "font slots must be unique",
334 ));
335 }
336 if !valid_sha256(&font.sha256.0) {
337 return Err(error(
338 "invalid_hash",
339 format!("$.fonts[{index}].sha256"),
340 "SHA-256 must be 64 lowercase hexadecimal characters",
341 ));
342 }
343 if font.aliases.len() > limits.max_aliases_per_font
344 || font.variations.len() > limits.max_variations_per_font
345 {
346 return Err(error(
347 "resource_limit",
348 format!("$.fonts[{index}]"),
349 "font metadata exceeds its limit",
350 ));
351 }
352 validate_aliases(font, index)?;
353 validate_variations(font, index)
354}
355
356fn validate_aliases(font: &FontBundleEntry, index: usize) -> Result<(), ValidationError> {
357 let mut aliases = HashSet::with_capacity(font.aliases.len());
358 if font
359 .aliases
360 .iter()
361 .any(|alias| alias.is_empty() || !aliases.insert(alias))
362 {
363 return Err(error(
364 "invalid_alias",
365 format!("$.fonts[{index}].aliases"),
366 "font aliases must be nonempty and unique within an entry",
367 ));
368 }
369 Ok(())
370}
371
372fn validate_variations(font: &FontBundleEntry, index: usize) -> Result<(), ValidationError> {
373 let mut axes = HashSet::with_capacity(font.variations.len());
374 for (variation_index, variation) in font.variations.iter().enumerate() {
375 if !valid_tag(&variation.axis.0) || !axes.insert(&variation.axis.0) {
376 return Err(error(
377 "invalid_variation",
378 format!("$.fonts[{index}].variations[{variation_index}]"),
379 "variation axes must be finite, valid, and unique",
380 ));
381 }
382 }
383 Ok(())
384}
385
386fn valid_sha256(value: &str) -> bool {
387 value.len() == 64
388 && value
389 .bytes()
390 .all(|byte| byte.is_ascii_digit() || (b'a'..=b'f').contains(&byte))
391}
392
393fn sha256_matches(buffer: &[u8], expected: &str) -> bool {
394 const HEX: &[u8; 16] = b"0123456789abcdef";
395 let (pairs, remainder) = expected.as_bytes().as_chunks::<2>();
396 if !remainder.is_empty() {
397 return false;
398 }
399 Sha256::digest(buffer)
400 .iter()
401 .zip(pairs)
402 .all(|(byte, pair)| *pair == [HEX[(byte >> 4) as usize], HEX[(byte & 0x0f) as usize]])
403}
404
405fn valid_tag(value: &str) -> bool {
406 value.len() == 4 && value.bytes().all(|byte| (b' '..=b'~').contains(&byte))
407}
408
409fn error(code: &'static str, path: impl Into<String>, message: &'static str) -> ValidationError {
410 validation_error(code, path, message)
411}