Debian Codegraph @

src/keywords/format.rs

raw symbols ◀ ▶ SCIP
1 Debian patch touch this file
1 //! Validator for `format` keyword.
2 use std::{
3 net::{Ipv4Addr, Ipv6Addr},
4 str::FromStr,
5 sync::Arc,
6 };
7
8 use email_address::EmailAddress;
9 use fancy_regex::Regex;
10 use serde_json::{Map, Value};
11 use std::sync::LazyLock;
12 use unicode_general_category::{get_general_category, GeneralCategory};
13 use uuid_simd::{parse_hyphenated, Out};
14
15 use crate::{
16 compiler, ecma,
17 error::ValidationError,
18 keywords::CompilationResult,
19 paths::{LazyLocation, Location},
20 thread::ThreadBound,
21 types::JsonType,
22 validator::{Validate, ValidationContext},
23 Draft,
24 };
25
26 static URI_TEMPLATE_RE: LazyLock<Regex> = LazyLock::new(|| {
27 Regex::new(
28 r#"^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*})*\z"#
29 )
30 .expect("Is a valid regex")
31 });
32
33 fn is_valid_json_pointer(pointer: &str) -> bool {
34 if pointer.is_empty() {
35 // An empty string is a valid JSON Pointer
36 return true;
37 }
38
39 let mut chars = pointer.chars();
40
41 // The first character must be a '/'
42 if chars.next() != Some('/') {
43 return false;
44 }
45 is_valid_json_pointer_impl(chars)
46 }
47
48 fn is_valid_relative_json_pointer(s: &str) -> bool {
49 let mut chars = s.chars();
50
51 // Parse the non-negative integer part
52 match chars.next() {
53 Some('0') => {
54 // If it starts with '0', it must be followed by '#' or '/'
55 match chars.next() {
56 Some('#') => chars.next().is_none(),
57 Some('/') => is_valid_json_pointer_impl(chars),
58 None => true,
59 _ => false,
60 }
61 }
62 Some(c) if c.is_ascii_digit() => {
63 // Parse the rest of the integer
64 while let Some(c) = chars.next() {
65 match c {
66 '#' => return chars.next().is_none(),
67 '/' => return is_valid_json_pointer_impl(chars),
68 c if c.is_ascii_digit() => {}
69 _ => return false,
70 }
71 }
72 // Valid if it's just a number
73 true
74 }
75 _ => false,
76 }
77 }
78
79 #[inline]
80 fn is_valid_json_pointer_impl<I: Iterator<Item = char>>(chars: I) -> bool {
81 let mut escaped = false;
82 for c in chars {
83 match c {
84 // '/' is only allowed as a separator between reference tokens
85 '/' if !escaped => escaped = false,
86 '~' if !escaped => escaped = true,
87 '0' | '1' if escaped => escaped = false,
88 // These ranges cover all allowed unescaped characters
89 '\x00'..='\x2E' | '\x30'..='\x7D' | '\x7F'..='\u{10FFFF}' if !escaped => {}
90 // Any other character or combination is invalid
91 _ => return false,
92 }
93 }
94 // If we end in an escaped state, it's invalid
95 !escaped
96 }
97
98 fn is_valid_date(date: &str) -> bool {
99 if date.len() != 10 {
100 return false;
101 }
102
103 let bytes = date.as_bytes();
104
105 // Check format: YYYY-MM-DD
106 if bytes[4] != b'-' || bytes[7] != b'-' {
107 return false;
108 }
109
110 // Parse year (YYYY)
111 let Some(year) = parse_four_digits(&bytes[0..4]) else {
112 return false;
113 };
114
115 // Parse month (MM)
116 let Some(month) = parse_two_digits(&bytes[5..7]) else {
117 return false;
118 };
119 if !(1..=12).contains(&month) {
120 return false;
121 }
122
123 // Parse day (DD)
124 let Some(day) = parse_two_digits(&bytes[8..10]) else {
125 return false;
126 };
127 if day == 0 {
128 return false;
129 }
130
131 // Check day validity
132 match month {
133 1 | 3 | 5 | 7 | 8 | 10 | 12 => day <= 31,
134 4 | 6 | 9 | 11 => day <= 30,
135 2 => {
136 if is_leap_year(year) {
137 day <= 29
138 } else {
139 day <= 28
140 }
141 }
142 _ => unreachable!("Month value is checked above"),
143 }
144 }
145
146 #[inline]
147 fn is_leap_year(year: u16) -> bool {
148 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
149 }
150
151 #[inline]
152 fn parse_four_digits(bytes: &[u8]) -> Option<u16> {
•153 // Little-endian layout: bytes[0] lands in the lowest byte of the u32.
154 // Check if all bytes are ASCII digits
•155 let value = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
156 let sub = value.wrapping_sub(0x3030_3030);
157 if sub.wrapping_add(0x0606_0606) & 0xF0F0_F0F0 != 0 {
158 return None;
159 }
•160 let val = (sub & 0x0F0F_0F0F).wrapping_mul(2561) >> 8;
161 Some(((val & 0x00FF_00FF).wrapping_mul(6_553_601) >> 16) as u16)
162 }
163
164 #[inline]
165 fn parse_two_digits(bytes: &[u8]) -> Option<u8> {
•166 // Little-endian layout: bytes[0] lands in the low byte of the u16.
167 // Check if all bytes are ASCII digits
168 let value = u16::from_le_bytes([bytes[0], bytes[1]]);
169 let sub = value.wrapping_sub(0x3030);
170 if sub.wrapping_add(0x0606) & 0xF0F0 != 0 {
171 return None;
172 }
•173 Some(((sub & 0x0F0F).wrapping_mul(2561) >> 8) as u8)
174 }
175
176 macro_rules! handle_offset {
177 ($sign:tt, $i:ident, $bytes:expr, $hour:expr, $minute:expr, $second:expr) => {{
178 if $bytes.len() - $i != 6 {
179 return false;
180 }
181 $i += 1;
182 if $bytes[$i + 2] != b':' {
183 return false;
184 }
185 let Some(offset_hh) = parse_two_digits(&$bytes[$i..$i + 2]) else {
186 return false;
187 };
188 let Some(offset_mm) = parse_two_digits(&$bytes[$i + 3..$i + 5]) else {
189 return false;
190 };
191 if offset_hh > 23 || offset_mm > 59 {
192 return false;
193 }
194
195 if $second == 60 {
196 let mut utc_hh = i16::from($hour);
197 let mut utc_mm = i16::from($minute);
198 let offset_hh = i16::from(offset_hh);
199 let offset_mm = i16::from(offset_mm);
200
201 // Apply offset based on the sign (+ or -)
202 utc_hh $sign offset_hh;
203 utc_mm $sign offset_mm;
204
205 // Adjust for minute overflow/underflow
206 utc_hh += utc_mm / 60;
207 utc_mm %= 60;
208 if utc_mm < 0 {
209 utc_mm += 60;
210 utc_hh -= 1;
211 }
212
213 // Adjust for hour overflow/underflow
214 utc_hh = (utc_hh + 24) % 24;
215 utc_hh == 23 && utc_mm == 59
216 } else {
217 true
218 }
219 }};
220 }
221
222 fn is_valid_time(time: &str) -> bool {
223 let bytes = time.as_bytes();
224 let len = bytes.len();
225
226 if len < 9 {
227 // Minimum valid time is "HH:MM:SSZ"
228 return false;
229 }
230
231 // Check HH:MM:SS format
232 if bytes[2] != b':' || bytes[5] != b':' {
233 return false;
234 }
235
236 // Parse hour (HH)
237 let Some(hour) = parse_two_digits(&bytes[..2]) else {
238 return false;
239 };
240 // Parse minute (MM)
241 let Some(minute) = parse_two_digits(&bytes[3..5]) else {
242 return false;
243 };
244 // Parse second (SS)
245 let Some(second) = parse_two_digits(&bytes[6..8]) else {
246 return false;
247 };
248
249 if hour > 23 || minute > 59 || second > 60 {
250 return false;
251 }
252
253 let mut i = 8;
254
255 // Check fractional seconds
256 if i < len && bytes[i] == b'.' {
257 i += 1;
258 let mut has_digit = false;
259 while i < len && bytes[i].is_ascii_digit() {
260 has_digit = true;
261 i += 1;
262 }
263 if !has_digit {
264 return false;
265 }
266 }
267
268 // Check offset
269 if i == len {
270 return false;
271 }
272
273 match bytes[i] {
274 b'Z' | b'z' => i == len - 1 && (second != 60 || (hour == 23 && minute == 59)),
275 b'+' => handle_offset!(-=, i, bytes, hour, minute, second),
276 b'-' => handle_offset!(+=, i, bytes, hour, minute, second),
277 _ => false,
278 }
279 }
280
281 fn is_valid_datetime(datetime: &str) -> bool {
282 // Find the position of 'T' or 't' separator
283 let Some(t_pos) = datetime.bytes().position(|b| b == b'T' || b == b't') else {
284 return false;
285 };
286
287 // Split the string into date and time parts
288 let (date_part, time_part) = datetime.split_at(t_pos);
289
290 is_valid_date(date_part) && is_valid_time(&time_part[1..])
291 }
292
293 fn is_valid_email_impl<F>(email: &str, is_valid_hostname_impl: F) -> bool
294 where
295 F: Fn(&str) -> bool,
296 {
297 if let Ok(parsed) = EmailAddress::from_str(email) {
298 let domain = parsed.domain();
299 if let Some(domain) = domain.strip_prefix('[').and_then(|d| d.strip_suffix(']')) {
300 if let Some(domain) = domain.strip_prefix("IPv6:") {
301 domain.parse::<Ipv6Addr>().is_ok()
302 } else {
303 domain.parse::<Ipv4Addr>().is_ok()
304 }
305 } else {
306 is_valid_hostname_impl(domain)
307 }
308 } else {
309 false
310 }
311 }
312
313 fn is_valid_email(email: &str) -> bool {
314 is_valid_email_impl(email, is_valid_hostname)
315 }
316
317 fn is_valid_idn_email(email: &str) -> bool {
318 is_valid_email_impl(email, is_valid_idn_hostname)
319 }
320
321 fn is_valid_hostname(hostname: &str) -> bool {
322 const VALID_CHARS: [bool; 256] = {
323 let mut table = [false; 256];
324 let mut byte: u8 = 0;
325 while byte < 255 {
326 table[byte as usize] = matches!(byte, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-');
327 byte += 1;
328 }
329 // Handle byte 255 separately to avoid overflow
330 table[255] = matches!(255u8, b'a'..=b'z' | b'A'..=b'Z' | b'0'..=b'9' | b'-');
331 table
332 };
333
334 fn label_allows_punycode(label: &[u8]) -> bool {
335 label.len() >= 4
336 && label[0] == b'x'
337 && label[1] == b'n'
338 && label[2] == b'-'
339 && label[3] == b'-'
340 }
341
342 fn validate_label(label: &[u8]) -> bool {
343 if label.is_empty()
344 || label.len() > 63
345 || label[0] == b'-'
346 || *label.last().unwrap() == b'-'
347 {
348 return false;
349 }
350
351 if label.len() >= 4 && label[2] == b'-' && label[3] == b'-' && !label_allows_punycode(label)
352 {
353 return false;
354 }
355
356 true
357 }
358
359 fn contains_punycode_label(hostname: &[u8]) -> bool {
360 hostname.split(|&b| b == b'.').any(|label| {
361 label.len() >= 4
362 && label[0] == b'x'
363 && label[1] == b'n'
364 && label[2] == b'-'
365 && label[3] == b'-'
366 })
367 }
368
369 let hostname_bytes = hostname.as_bytes();
370 let len = hostname_bytes.len();
371 if len == 0 || len > 253 || hostname_bytes[len - 1] == b'.' {
372 return false;
373 }
374
375 let mut label_start = 0;
376 let mut i = 0;
377
378 while i < len {
379 if hostname_bytes[i] == b'.' {
380 if !validate_label(&hostname_bytes[label_start..i]) {
381 return false;
382 }
383 label_start = i + 1;
384 } else if !VALID_CHARS[hostname_bytes[i] as usize] {
385 return false;
386 }
387 i += 1;
388 }
389
390 if !validate_label(&hostname_bytes[label_start..]) {
391 return false;
392 }
393
394 if contains_punycode_label(hostname_bytes) {
395 use idna::punycode;
396 for label in hostname_bytes.split(|&b| b == b'.') {
397 if label.len() >= 4
398 && label[0] == b'x'
399 && label[1] == b'n'
400 && label[2] == b'-'
401 && label[3] == b'-'
402 {
403 let payload =
404 std::str::from_utf8(&label[4..]).expect("ASCII label already validated");
405 let Some(decoded) = punycode::decode_to_string(payload) else {
406 return false;
407 };
408 if !validate_unicode_label(&decoded) {
409 return false;
410 }
411 }
412 }
413 }
414
415 true
416 }
417
418 fn validate_unicode_label(label: &str) -> bool {
419 let mut chars = label.chars().peekable();
420 if let Some(&first) = chars.peek() {
421 let category = get_general_category(first);
422 if matches!(
423 category,
424 GeneralCategory::SpacingMark
425 | GeneralCategory::NonspacingMark
426 | GeneralCategory::EnclosingMark
427 ) {
428 return false;
429 }
430 }
431 let mut previous = None;
432 let mut has_katakana_middle_dot = false;
433 let mut has_hiragana_katakana_han = false;
434 let mut has_arabic_indic_digits = false;
435 let mut has_extended_arabic_indic_digits = false;
436
437 while let Some(current) = chars.next() {
438 match current {
439 // ZERO WIDTH JOINER
440 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.2
441 '\u{200D}'
442 if !previous.is_some_and(|prev| {
443 matches!(
444 prev,
445 '\u{094D}'
446 | '\u{09CD}'
447 | '\u{0A4D}'
448 | '\u{0ACD}'
449 | '\u{0B4D}'
450 | '\u{0BCD}'
451 | '\u{0C4D}'
452 | '\u{0CCD}'
453 | '\u{0D4D}'
454 | '\u{0DCA}'
455 | '\u{0E3A}'
456 | '\u{0F84}'
457 | '\u{1039}'
458 | '\u{1714}'
459 | '\u{1734}'
460 | '\u{17D2}'
461 | '\u{1A60}'
462 | '\u{1B44}'
463 | '\u{1BAA}'
464 | '\u{1BF2}'
465 | '\u{1BF3}'
466 | '\u{2D7F}'
467 | '\u{A806}'
468 | '\u{A8C4}'
469 | '\u{A953}'
470 | '\u{ABED}'
471 | '\u{10A3F}'
472 | '\u{11046}'
473 | '\u{1107F}'
474 | '\u{110B9}'
475 | '\u{11133}'
476 | '\u{111C0}'
477 | '\u{11235}'
478 | '\u{112EA}'
479 | '\u{1134D}'
480 | '\u{11442}'
481 | '\u{114C2}'
482 | '\u{115BF}'
483 | '\u{1163F}'
484 | '\u{116B6}'
485 | '\u{1172B}'
486 | '\u{11839}'
487 | '\u{119E0}'
488 | '\u{11A34}'
489 | '\u{11A47}'
490 | '\u{11A99}'
491 | '\u{11C3F}'
492 | '\u{11D44}'
493 | '\u{11D45}'
494 | '\u{11D97}'
495 )
496 }) =>
497 {
498 return false;
499 }
500 // MIDDLE DOT
501 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.3
502 '\u{00B7}' if previous != Some('l') || chars.peek() != Some(&'l') => return false,
503 // Greek KERAIA
504 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.4
505 '\u{0375}'
506 if !chars
507 .peek()
508 .is_some_and(|next| ('\u{0370}'..='\u{03FF}').contains(next)) =>
509 {
510 return false
511 }
512 // Hebrew GERESH and GERSHAYIM
513 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.5
514 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.6
515 '\u{05F3}' | '\u{05F4}'
516 if !previous.is_some_and(|prev| ('\u{0590}'..='\u{05FF}').contains(&prev)) =>
517 {
518 return false
519 }
520 // KATAKANA MIDDLE DOT
521 '\u{30FB}' => has_katakana_middle_dot = true,
522 // Hiragana, Katakana, or Han
523 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.7
524 '\u{3040}'..='\u{309F}' | '\u{30A0}'..='\u{30FF}' | '\u{4E00}'..='\u{9FFF}' => {
525 has_hiragana_katakana_han = true;
526 }
527 // ARABIC-INDIC DIGITS
528 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.8
529 '\u{0660}'..='\u{0669}' => has_arabic_indic_digits = true,
530 // EXTENDED ARABIC-INDIC DIGITS
531 // https://www.rfc-editor.org/rfc/rfc5892#appendix-A.9
532 '\u{06F0}'..='\u{06F9}' => has_extended_arabic_indic_digits = true,
533 // DISALLOWED
534 '\u{0640}' | '\u{07FA}' | '\u{302E}' | '\u{302F}' | '\u{3031}' | '\u{3032}'
535 | '\u{3033}' | '\u{3034}' | '\u{3035}' | '\u{303B}' => return false,
536
537 _ => {}
538 }
539 previous = Some(current);
540 }
541
542 if (has_katakana_middle_dot && !has_hiragana_katakana_han)
543 || (has_arabic_indic_digits && has_extended_arabic_indic_digits)
544 {
545 return false;
546 }
547
548 true
549 }
550
551 fn is_valid_idn_hostname(hostname: &str) -> bool {
552 use idna::uts46::{AsciiDenyList, DnsLength, Hyphens, Uts46};
553
554 let Ok(ascii_hostname) = Uts46::new().to_ascii(
555 hostname.as_bytes(),
556 AsciiDenyList::STD3,
557 // Prohibit hyphens in the first, third, fourth, and last position in the label
558 Hyphens::Check,
559 DnsLength::Verify,
560 ) else {
561 return false;
562 };
563
564 if !is_valid_hostname(&ascii_hostname) {
565 return false;
566 }
567
568 let (unicode_hostname, _) = Uts46::new().to_unicode(
569 ascii_hostname.as_bytes(),
570 AsciiDenyList::EMPTY,
571 Hyphens::Allow,
572 );
573
574 unicode_hostname
575 .split('.')
576 .all(|label| !label.is_empty() && validate_unicode_label(label))
577 }
578
579 #[inline]
580 fn unit_index(units: &[u8], unit: u8) -> Option<usize> {
581 units.iter().position(|&u| u == unit)
582 }
583
584 fn is_valid_duration(duration: &str) -> bool {
585 let bytes = duration.as_bytes();
586 let len = bytes.len();
587
588 if len < 2 || bytes[0] != b'P' {
589 return false;
590 }
591
592 let mut i = 1;
593 let mut has_component = false;
594 let mut has_time = false;
595 let mut last_date_unit = 0;
596 let mut last_time_unit = 0;
597 let mut has_weeks = false;
598 let mut has_time_component = false;
599 let mut seen_units = 0u8;
600
601 let date_units = [b'Y', b'M', b'W', b'D'];
602 let time_units = [b'H', b'M', b'S'];
603
604 while i < len {
605 if bytes[i] == b'T' {
606 if has_time {
607 return false;
608 }
609 has_time = true;
610 i += 1;
611 continue;
612 }
613
614 let start = i;
615 while i < len && bytes[i].is_ascii_digit() {
616 i += 1;
617 }
618
619 if i == start || i == len {
620 return false;
621 }
622
623 let unit = bytes[i];
624
625 if !has_time {
626 if let Some(idx) = unit_index(&date_units, unit) {
627 if unit == b'W' {
628 if has_component {
629 return false;
630 }
631 has_weeks = true;
632 } else if has_weeks {
633 return false;
634 }
635 if idx < last_date_unit || (seen_units & (1 << idx) != 0) {
636 return false;
637 }
638 seen_units |= 1 << idx;
639 last_date_unit = idx;
640 } else {
641 return false;
642 }
643 } else if let Some(idx) = unit_index(&time_units, unit) {
644 if idx < last_time_unit || (seen_units & (1 << (idx + 4)) != 0) {
645 return false;
646 }
647 seen_units |= 1 << (idx + 4);
648 last_time_unit = idx;
649 has_time_component = true;
650 } else {
651 return false;
652 }
653
654 has_component = true;
655 i += 1;
656 }
657
658 has_component && (!has_time || has_time_component)
659 }
660
661 fn is_valid_ipv4(ip: &str) -> bool {
662 Ipv4Addr::from_str(ip).is_ok()
663 }
664
665 fn is_valid_ipv6(ip: &str) -> bool {
666 Ipv6Addr::from_str(ip).is_ok()
667 }
668
669 fn is_valid_iri(iri: &str) -> bool {
670 referencing::Iri::parse(iri).is_ok()
671 }
672
673 fn is_valid_iri_reference(iri_reference: &str) -> bool {
674 referencing::IriRef::parse(iri_reference).is_ok()
675 }
676
677 fn is_valid_uri(uri: &str) -> bool {
678 referencing::Uri::parse(uri).is_ok()
679 }
680
681 fn is_valid_uri_reference(uri_reference: &str) -> bool {
682 referencing::UriRef::parse(uri_reference).is_ok()
683 }
684
685 fn is_valid_regex(regex: &str) -> bool {
686 ecma::to_rust_regex(regex).is_ok()
687 }
688
689 fn is_valid_uri_template(uri_template: &str) -> bool {
690 URI_TEMPLATE_RE
691 .is_match(uri_template)
692 .expect("Simple URI_TEMPLATE_RE pattern")
693 }
694
695 fn is_valid_uuid(uuid: &str) -> bool {
696 let mut out = [0; 16];
697 parse_hyphenated(uuid.as_bytes(), Out::from_mut(&mut out)).is_ok()
698 }
699
700 macro_rules! format_validators {
701 ($(($validator:ident, $format:expr, $validation_fn:ident)),+ $(,)?) => {
702 $(
703 struct $validator {
704 location: Location,
705 }
706
707 impl $validator {
708 pub(crate) fn compile<'a>(ctx: &compiler::Context) -> CompilationResult<'a> {
709 let location = ctx.location().join("format");
710 Ok(Box::new($validator { location }))
711 }
712 }
713
714 impl Validate for $validator {
715 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
716 if let Value::String(item) = instance {
717 $validation_fn(item)
718 } else {
719 true
720 }
721 }
722
723 fn validate<'i>(
724 &self,
725 instance: &'i Value,
726 location: &LazyLocation,
727 ctx: &mut ValidationContext,
728 ) -> Result<(), ValidationError<'i>> {
729 if let Value::String(_item) = instance {
730 if !self.is_valid(instance, ctx) {
731 return Err(ValidationError::format(
732 self.location.clone(),
733 location.into(),
734 instance,
735 $format,
736 ));
737 }
738 }
739 Ok(())
740 }
741 }
742 )+
743 };
744 }
745 format_validators!(
746 (DateValidator, "date", is_valid_date),
747 (DateTimeValidator, "date-time", is_valid_datetime),
748 (DurationValidator, "duration", is_valid_duration),
749 (EmailValidator, "email", is_valid_email),
750 (HostnameValidator, "hostname", is_valid_hostname),
751 (IdnEmailValidator, "idn-email", is_valid_idn_email),
752 (IdnHostnameValidator, "idn-hostname", is_valid_idn_hostname),
753 (IpV4Validator, "ipv4", is_valid_ipv4),
754 (IpV6Validator, "ipv6", is_valid_ipv6),
755 (IriValidator, "iri", is_valid_iri),
756 (
757 IriReferenceValidator,
758 "iri-reference",
759 is_valid_iri_reference
760 ),
761 (JsonPointerValidator, "json-pointer", is_valid_json_pointer),
762 (RegexValidator, "regex", is_valid_regex),
763 (
764 RelativeJsonPointerValidator,
765 "relative-json-pointer",
766 is_valid_relative_json_pointer
767 ),
768 (TimeValidator, "time", is_valid_time),
769 (UriValidator, "uri", is_valid_uri),
770 (
771 UriReferenceValidator,
772 "uri-reference",
773 is_valid_uri_reference
774 ),
775 (UriTemplateValidator, "uri-template", is_valid_uri_template),
776 (UuidValidator, "uuid", is_valid_uuid),
777 );
778
779 struct CustomFormatValidator {
780 location: Location,
781 format_name: String,
782 check: Arc<dyn Format>,
783 }
784 impl CustomFormatValidator {
785 pub(crate) fn compile<'a>(
786 ctx: &compiler::Context,
787 format_name: String,
788 check: Arc<dyn Format>,
789 ) -> CompilationResult<'a> {
790 let location = ctx.location().join("format");
791 Ok(Box::new(CustomFormatValidator {
792 location,
793 format_name,
794 check,
795 }))
796 }
797 }
798
799 impl Validate for CustomFormatValidator {
800 fn validate<'i>(
801 &self,
802 instance: &'i Value,
803 location: &LazyLocation,
804 ctx: &mut ValidationContext,
805 ) -> Result<(), ValidationError<'i>> {
806 if self.is_valid(instance, ctx) {
807 Ok(())
808 } else {
809 Err(ValidationError::format(
810 self.location.clone(),
811 location.into(),
812 instance,
813 self.format_name.clone(),
814 ))
815 }
816 }
817
818 fn is_valid(&self, instance: &Value, _ctx: &mut ValidationContext) -> bool {
819 if let Value::String(item) = instance {
820 self.check.is_valid(item)
821 } else {
822 true
823 }
824 }
825 }
826
827 pub(crate) trait Format: ThreadBound + 'static {
828 fn is_valid(&self, value: &str) -> bool;
829 }
830
831 impl<F> Format for F
832 where
833 F: Fn(&str) -> bool + ThreadBound + 'static,
834 {
835 #[inline]
836 fn is_valid(&self, value: &str) -> bool {
837 self(value)
838 }
839 }
840
841 #[inline]
842 pub(crate) fn compile<'a>(
843 ctx: &compiler::Context,
844 _: &'a Map<String, Value>,
845 schema: &'a Value,
846 ) -> Option<CompilationResult<'a>> {
847 if !ctx.validates_formats_by_default() {
848 return None;
849 }
850
851 if let Value::String(format) = schema {
852 if let Some((name, func)) = ctx.get_format(format) {
853 return Some(CustomFormatValidator::compile(
854 ctx,
855 name.clone(),
856 func.clone(),
857 ));
858 }
859 let draft = ctx.draft();
860 match format.as_str() {
861 "date" => Some(DateValidator::compile(ctx)),
862 "date-time" => Some(DateTimeValidator::compile(ctx)),
863 "duration" if draft >= Draft::Draft201909 => Some(DurationValidator::compile(ctx)),
864 "email" => Some(EmailValidator::compile(ctx)),
865 "hostname" => Some(HostnameValidator::compile(ctx)),
866 "idn-email" => Some(IdnEmailValidator::compile(ctx)),
867 "idn-hostname" if draft >= Draft::Draft7 => Some(IdnHostnameValidator::compile(ctx)),
868 "ipv4" => Some(IpV4Validator::compile(ctx)),
869 "ipv6" => Some(IpV6Validator::compile(ctx)),
870 "iri" if draft >= Draft::Draft7 => Some(IriValidator::compile(ctx)),
871 "iri-reference" if draft >= Draft::Draft7 => Some(IriReferenceValidator::compile(ctx)),
872 "json-pointer" if draft >= Draft::Draft6 => Some(JsonPointerValidator::compile(ctx)),
873 "regex" => Some(RegexValidator::compile(ctx)),
874 "relative-json-pointer" if draft >= Draft::Draft7 => {
875 Some(RelativeJsonPointerValidator::compile(ctx))
876 }
877 "time" => Some(TimeValidator::compile(ctx)),
878 "uri" => Some(UriValidator::compile(ctx)),
879 "uri-reference" if draft >= Draft::Draft6 => Some(UriReferenceValidator::compile(ctx)),
880 "uri-template" if draft >= Draft::Draft6 => Some(UriTemplateValidator::compile(ctx)),
881 "uuid" if draft >= Draft::Draft201909 => Some(UuidValidator::compile(ctx)),
882 name => {
883 if ctx.are_unknown_formats_ignored() {
884 None
885 } else {
886 Some(Err(ValidationError::custom(
887 Location::new().join("format"),
888 ctx.location().clone(),
889 schema,
890 format!("Unknown format: '{name}'. Adjust configuration to ignore unrecognized formats"),
891 )))
892 }
893 }
894 }
895 } else {
896 Some(Err(ValidationError::single_type_error(
897 Location::new(),
898 ctx.location().clone(),
899 schema,
900 JsonType::String,
901 )))
902 }
903 }
904
905 #[cfg(test)]
906 mod tests {
907 use referencing::Draft;
908 use serde_json::json;
909 use test_case::test_case;
910
911 use crate::tests_util;
912
913 use super::*;
914
•915 #[test_case(b"00" => Some(0); "min")]
916 #[test_case(b"09" => Some(9); "nine")]
917 #[test_case(b"10" => Some(10); "ten")]
918 #[test_case(b"59" => Some(59); "fifty-nine")]
919 #[test_case(b"99" => Some(99); "max")]
920 #[test_case(b"1a" => None; "alpha")]
921 #[test_case(b" 5" => None; "leading space")]
922 #[test_case(b":0" => None; "colon is not a digit")]
923 #[test_case(b";9" => None; "semicolon is not a digit")]
924 fn test_parse_two_digits(bytes: &[u8]) -> Option<u8> {
925 parse_two_digits(bytes)
926 }
927
928 #[test_case(b"0000" => Some(0); "zero")]
929 #[test_case(b"1970" => Some(1970); "epoch year")]
930 #[test_case(b"2023" => Some(2023); "recent year")]
931 #[test_case(b"9999" => Some(9999); "max")]
932 #[test_case(b"199x" => None; "trailing alpha")]
933 #[test_case(b" 999" => None; "leading space")]
934 #[test_case(b"20:3" => None; "colon is not a digit")]
935 fn test_parse_four_digits(bytes: &[u8]) -> Option<u16> {
936 parse_four_digits(bytes)
937 }
938
939 #[test]
940 fn ignored_format() {
941 let schema = json!({"format": "custom", "type": "string"});
942 let instance = json!("foo");
943 let validator = crate::validator_for(&schema).unwrap();
944 assert!(validator.is_valid(&instance));
945 }
946
947 #[test]
948 fn format_validation() {
949 let schema = json!({"format": "email", "type": "string"});
950 let email_instance = json!("[email protected]");
951 let not_email_instance = json!("foo");
952
953 let with_validation = crate::options()
954 .should_validate_formats(true)
955 .build(&schema)
956 .unwrap();
957 let without_validation = crate::options()
958 .should_validate_formats(false)
959 .build(&schema)
960 .unwrap();
961
962 assert!(with_validation.is_valid(&email_instance));
963 assert!(!with_validation.is_valid(&not_email_instance));
964 assert!(without_validation.is_valid(&email_instance));
965 assert!(without_validation.is_valid(&not_email_instance));
966 }
967
968 #[test]
969 fn ecma_regex() {
970 // See GH-230
971 let schema = json!({"format": "regex", "type": "string"});
972 let instance = json!("^\\cc$");
973 let validator = crate::validator_for(&schema).unwrap();
974 assert!(validator.is_valid(&instance));
975 }
976
977 #[test]
978 fn location() {
979 tests_util::assert_schema_location(&json!({"format": "date"}), &json!("bla"), "/format");
980 }
981
982 #[test]
983 fn uuid() {
984 let schema = json!({"format": "uuid", "type": "string"});
985
986 let passing_instance = json!("f308a72c-fa84-11eb-9a03-0242ac130003");
987 let failing_instance = json!("1");
988
989 let validator = crate::options()
990 .with_draft(Draft::Draft201909)
991 .should_validate_formats(true)
992 .build(&schema)
993 .unwrap();
994
995 assert!(validator.is_valid(&passing_instance));
996 assert!(!validator.is_valid(&failing_instance));
997 }
998
999 #[test]
1000 fn uri() {
1001 let schema = json!({"format": "uri", "type": "string"});
1002
1003 let passing_instance = json!("https://phillip.com");
1004 let failing_instance = json!("redis");
1005
1006 tests_util::is_valid(&schema, &passing_instance);
1007 tests_util::is_not_valid(&schema, &failing_instance);
1008 }
1009
1010 #[test_case("P1Y1Y")]
1011 #[test_case("PT1H1H")]
1012 fn test_invalid_duration(input: &str) {
1013 assert!(!is_valid_duration(input));
1014 }
1015
1016 #[test]
1017 fn unknown_formats_should_not_be_ignored() {
1018 let schema = json!({ "format": "custom", "type": "string"});
1019 let error = crate::options()
1020 .should_validate_formats(true)
1021 .should_ignore_unknown_formats(false)
1022 .build(&schema)
1023 .expect_err("the validation error should be returned");
1024
1025 assert_eq!(
1026 error.to_string(),
1027 "Unknown format: 'custom'. Adjust configuration to ignore unrecognized formats"
1028 );
1029 }
1030
1031 #[test_case("2023-01-01", true; "valid regular date")]
1032 #[test_case("2020-02-29", true; "valid leap year date")]
1033 #[test_case("2021-02-28", true; "valid non-leap year date")]
1034 #[test_case("1900-02-28", true; "valid century non-leap year")]
1035 #[test_case("2000-02-29", true; "valid leap century year")]
1036 #[test_case("1999-12-31", true; "valid end of year date")]
1037 #[test_case("202-12-01", false; "invalid short year")]
1038 #[test_case("2023-1-01", false; "invalid short month")]
1039 #[test_case("2023-12-1", false; "invalid short day")]
1040 #[test_case("2023/12/01", false; "invalid separators")]
1041 #[test_case("2023-13-01", false; "invalid month too high")]
1042 #[test_case("2023-00-01", false; "invalid month too low")]
1043 #[test_case("2023-12-32", false; "invalid day too high")]
1044 #[test_case("2023-11-31", false; "invalid day for 30-day month")]
1045 #[test_case("2023-02-30", false; "invalid day for February in non-leap year")]
1046 #[test_case("2021-02-29", false; "invalid day for non-leap year")]
1047 #[test_case("2023-12-00", false; "invalid day too low")]
1048 #[test_case("99999-12-01", false; "year too long")]
1049 #[test_case("1900-02-29", false; "invalid leap century non-leap year")]
1050 #[test_case("2000-02-30", false; "invalid day for leap century year")]
1051 #[test_case("2400-02-29", true; "valid leap year in distant future")]
1052 #[test_case("0000-01-01", true; "valid boundary start date")]
1053 #[test_case("9999-12-31", true; "valid boundary end date")]
1054 #[test_case("aaaa-01-12", false; "Malformed (letters in year)")]
1055 #[test_case("2000-bb-12", false; "Malformed (letters in month)")]
1056 #[test_case("2000-01-cc", false; "Malformed (letters in day)")]
•1057 #[test_case("20:3-01-15", false; "colon in year")]
1058 #[test_case("20;3-01-15", false; "semicolon in year")]
1059 fn test_is_valid_date(input: &str, expected: bool) {
1060 assert_eq!(is_valid_date(input), expected);
1061 }
1062
1063 #[test_case("23:59:59Z", true; "valid time with Z")]
1064 #[test_case("00:00:00Z", true; "valid midnight time with Z")]
1065 #[test_case("12:30:45.123Z", true; "valid time with fractional seconds and Z")]
1066 #[test_case("23:59:60Z", true; "valid leap second UTC time")]
1067 #[test_case("12:30:45+01:00", true; "valid time with positive offset")]
1068 #[test_case("12:30:45-01:00", true; "valid time with negative offset")]
1069 #[test_case("23:59:60+00:00", true; "valid leap second with offset UTC 00:00")]
1070 #[test_case("23:59:59+01:00", true; "valid time with +01:00 offset")]
1071 #[test_case("23:59:59A", false; "invalid time with non-Z/non-offset letter")]
1072 #[test_case("12:3:45Z", false; "invalid time with missing digit in minute")]
1073 #[test_case("12:30:4Z", false; "invalid time with missing digit in second")]
1074 #[test_case("12-30-45Z", false; "invalid time with wrong separator")]
1075 #[test_case("12:30:45Z+01:00", false; "invalid time with Z and offset together")]
1076 #[test_case("12:30:45A01:00", false; "invalid time with wrong separator between time and offset")]
1077 #[test_case("12:30:45++01:00", false; "invalid double plus in offset")]
1078 #[test_case("12:30:45+01:60", false; "invalid minute in offset")]
1079 #[test_case("12:30:45+24:00", false; "invalid hour in offset")]
1080 #[test_case("12:30:45.", false; "invalid time with incomplete fractional second")]
1081 #[test_case("24:00:00Z", false; "invalid hour > 23")]
1082 #[test_case("12:60:00Z", false; "invalid minute > 59")]
1083 #[test_case("12:30:61Z", false; "invalid second > 60")]
1084 #[test_case("12:30:60+01:00", false; "invalid leap second with non-UTC offset")]
1085 #[test_case("23:59:60Z+01:00", false; "invalid leap second with non-zero offset")]
1086 #[test_case("23:59:60+00:30", false; "invalid leap second with non-zero minute offset")]
1087 #[test_case("23:59:60Z", true; "valid leap second at the end of day")]
1088 #[test_case("23:59:60+00:00", true; "valid leap second with zero offset")]
1089 #[test_case("ab:59:59Z", false; "invalid time with letters in hour")]
1090 #[test_case("23:ab:59Z", false; "invalid time with letters in minute")]
1091 #[test_case("23:59:abZ", false; "invalid time with letters in second")]
1092 #[test_case("23:59:59aZ", false; "invalid time with letter after seconds")]
1093 #[test_case("12:30:45+ab:00", false; "invalid offset hour with letters")]
1094 #[test_case("12:30:45+01:ab", false; "invalid offset minute with letters")]
1095 #[test_case("12:30:45.abcZ", false; "invalid fractional seconds with letters")]
1096 fn test_is_valid_time(input: &str, expected: bool) {
1097 assert_eq!(is_valid_time(input), expected);
1098 }
1099
1100 #[test]
1101 fn test_is_valid_datetime() {
1102 assert!(!is_valid_datetime(""));
1103 }
1104
1105 #[test_case("127.0.0.1", true)]
1106 #[test_case("192.168.1.1", true)]
1107 #[test_case("10.0.0.1", true)]
1108 #[test_case("0.0.0.0", true)]
1109 #[test_case("256.1.2.3", false; "first octet too large")]
1110 #[test_case("1.256.3.4", false; "second octet too large")]
1111 #[test_case("1.2.256.4", false; "third octet too large")]
1112 #[test_case("1.2.3.256", false; "fourth octet too large")]
1113 #[test_case("01.2.3.4", false; "leading zero in first octet")]
1114 #[test_case("1.02.3.4", false; "leading zero in second octet")]
1115 #[test_case("1.2.03.4", false; "leading zero in third octet")]
1116 #[test_case("1.2.3.04", false; "leading zero in fourth octet")]
1117 #[test_case("1.2.3", false; "too few octets")]
1118 #[test_case("1.2.3.4.5", false; "too many octets")]
1119 fn ip_v4(input: &str, expected: bool) {
1120 let validator = crate::options()
1121 .should_validate_formats(true)
1122 .build(&json!({"format": "ipv4", "type": "string"}))
1123 .expect("Invalid schema");
1124 assert_eq!(validator.is_valid(&json!(input)), expected);
1125 }
1126
1127 #[test]
1128 fn test_is_valid_datetime_panic() {
1129 is_valid_datetime("2624-04-25t23:14:04-256\x112");
1130 }
1131
1132 #[test_case("example.com" ; "simple valid hostname")]
1133 #[test_case("xn--bcher-kva.com" ; "valid punycode")]
1134 #[test_case("münchen.de" ; "valid IDN")]
1135 #[test_case("test\u{094D}\u{200D}example.com" ; "valid zero width joiner after virama")]
1136 #[test_case("۱۲۳.example.com" ; "valid extended arabic-indic digits")]
1137 #[test_case("ひらがな・カタカナ.com" ; "valid katakana middle dot")]
1138 fn test_valid_idn_hostnames(input: &str) {
1139 assert!(is_valid_idn_hostname(input));
1140 }
1141
1142 #[test_case("xn--ll-0ea" ; "punycode with valid middle dot context")]
1143 #[test_case("xn--11b2ezcw70k" ; "zero width joiner preceded by virama")]
1144 fn test_valid_punycode_hostnames(input: &str) {
1145 assert!(is_valid_hostname(input));
1146 }
1147
1148 #[test_case("ex--ample.com" ; "hyphen at 3rd & 4th position")]
1149 #[test_case("-example.com" ; "leading hyphen")]
1150 #[test_case("example-.com" ; "trailing hyphen")]
1151 #[test_case("xn--example.com" ; "invalid punycode")]
1152 #[test_case("xn--x" ; "too short punycode label")]
1153 #[test_case("xn--vek" ; "katakana middle dot without companions")]
1154 #[test_case("xn--l-fda" ; "middle dot with nothing preceding")]
1155 #[test_case("xn--l-gda" ; "middle dot with nothing following")]
1156 #[test_case("xn--02b508i" ; "zero width joiner not preceded by virama")]
1157 #[test_case("xn--a-2hc5h" ; "hebrew geresh not preceded by hebrew")]
1158 #[test_case("xn--a-2hc8h" ; "hebrew gershayim not preceded by hebrew")]
1159 #[test_case("test\u{200D}example.com" ; "zero width joiner not after virama")]
1160 #[test_case("test\u{0061}\u{200D}example.com" ; "zero width joiner after non-virama")]
1161 #[test_case("" ; "empty string")]
1162 #[test_case("." ; "single dot")]
1163 #[test_case("example..com" ; "consecutive dots")]
1164 #[test_case("exa mple.com" ; "contains space")]
1165 #[test_case("example.com." ; "trailing dot")]
1166 #[test_case("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com" ; "too long")]
1167 #[test_case("xn--bcher-.com" ; "invalid punycode with hyphen")]
1168 #[test_case("١۲٣.example.com" ; "mixed arabic-indic digits")]
1169 #[test_case("example・com" ; "katakana middle dot without hiragana/katakana/han")]
1170 fn test_invalid_idn_hostnames(input: &str) {
1171 assert!(!is_valid_idn_hostname(input));
1172 }
1173
1174 #[test_case("xn--l-fda" ; "middle dot with nothing preceding")]
1175 #[test_case("xn--l-gda" ; "middle dot with nothing following")]
1176 #[test_case("xn--02b508i" ; "zero width joiner not preceded by anything")]
1177 #[test_case("xn--11b2er09f" ; "zero width joiner not preceded by virama")]
1178 #[test_case("xn--hello-zed" ; "punycode beginning with nonspacing mark")]
1179 #[test_case("xn--hello-txk" ; "punycode beginning with spacing combining mark")]
1180 #[test_case("xn--hello-6bf" ; "punycode beginning with enclosing mark")]
1181 #[test_case("XN--aa---o47jg78q" ; "uppercase punycode prefix rejected")]
1182 fn test_invalid_punycode_hostnames(input: &str) {
1183 assert!(!is_valid_hostname(input));
1184 }
1185
1186 #[test]
1187 fn test_invalid_hostname() {
1188 assert!(!is_valid_hostname("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.com"));
1189 }
1190
1191 #[test_case(""; "empty string")]
1192 #[test_case("/"; "root")]
1193 #[test_case("/foo"; "simple key")]
1194 #[test_case("/foo/0"; "array index")]
1195 #[test_case("/foo/bar"; "nested keys")]
1196 #[test_case("/f~0o/b~1r"; "escaped characters")]
1197 #[test_case("/foo/bar/"; "trailing slash")]
1198 #[test_case("/foo//bar"; "empty reference token")]
1199 fn test_valid_json_pointer(pointer: &str) {
1200 assert!(is_valid_json_pointer(pointer));
1201 }
1202
1203 #[test_case("foo"; "missing leading slash")]
1204 #[test_case("/foo/~"; "incomplete escape")]
1205 #[test_case("/foo/~2"; "invalid escape")]
1206 #[test_case("/foo\x7E"; "unescaped tilde")]
1207 fn test_invalid_json_pointer(pointer: &str) {
1208 assert!(!is_valid_json_pointer(pointer));
1209 }
1210
1211 #[test_case("0"; "zero")]
1212 #[test_case("1"; "positive integer")]
1213 #[test_case("10"; "multi-digit integer")]
1214 #[test_case("0#"; "zero with hash")]
1215 #[test_case("1#"; "positive integer with hash")]
1216 #[test_case("0/"; "zero with slash")]
1217 #[test_case("1/foo"; "integer with json pointer")]
1218 #[test_case("10/foo/bar"; "multi-digit integer with json pointer")]
1219 fn test_valid_relative_json_pointer(pointer: &str) {
1220 assert!(is_valid_relative_json_pointer(pointer));
1221 }
1222
1223 #[test_case(""; "empty string")]
1224 #[test_case("-1"; "negative integer")]
1225 #[test_case("01"; "leading zero")]
1226 #[test_case("1.5"; "decimal")]
1227 #[test_case("a"; "non-digit")]
1228 #[test_case("1a"; "digit followed by non-digit")]
1229 #[test_case("1#/"; "hash not at end")]
1230 #[test_case("1/~"; "incomplete escape in json pointer")]
1231 fn test_invalid_relative_json_pointer(pointer: &str) {
1232 assert!(!is_valid_relative_json_pointer(pointer));
1233 }
1234 }