1use crate::lint_input::{Visitor, join_pointer, parse_json_number_text, walk};
4use crate::suffix::{currency_code, has_registered_suffix, has_suffix_ci};
5use crate::{
6 ProtocolViolation, is_valid_bcp47, is_valid_rfc3339, is_valid_rfc3339_date,
7 is_valid_rfc3339_time, normalize_utc_offset, validate_protocol_event,
8};
9use serde::Serialize;
10use serde_json::{Number, Value};
11use std::fmt;
12
13const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
14
15#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
17pub struct LintFinding {
18 pub rule_id: String,
19 pub pointer: String,
20 pub message: String,
21}
22
23impl LintFinding {
24 fn new(rule_id: &str, pointer: impl Into<String>, message: impl Into<String>) -> Self {
25 Self {
26 rule_id: rule_id.to_owned(),
27 pointer: pointer.into(),
28 message: message.into(),
29 }
30 }
31}
32
33#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
35pub struct LintOptions {
36 untyped_text_scalars: bool,
37 schema_properties: bool,
38}
39
40impl LintOptions {
41 pub const fn new() -> Self {
43 Self {
44 untyped_text_scalars: false,
45 schema_properties: false,
46 }
47 }
48
49 pub const fn untyped_text_scalars(mut self, untyped_text_scalars: bool) -> Self {
51 self.untyped_text_scalars = untyped_text_scalars;
52 self
53 }
54
55 pub const fn schema_properties(mut self) -> Self {
57 self.schema_properties = true;
58 self
59 }
60}
61
62pub fn lint_value(value: &Value, options: LintOptions) -> Vec<LintFinding> {
64 lint_value_with_key(value, None, options)
65}
66
67pub fn lint_field_value(key: &str, value: &Value, options: LintOptions) -> Vec<LintFinding> {
70 lint_value_with_key(value, Some(key), options)
71}
72
73fn lint_value_with_key(value: &Value, key: Option<&str>, options: LintOptions) -> Vec<LintFinding> {
74 let mut checks = ContractChecks {
75 untyped: options.untyped_text_scalars,
76 findings: Vec::new(),
77 };
78 walk(&mut checks, value, key, "", options.schema_properties);
79 checks.findings
80}
81
82struct ContractChecks {
83 untyped: bool,
84 findings: Vec<LintFinding>,
85}
86
87impl Visitor for ContractChecks {
88 fn field(&mut self, key: &str, value: &Value, pointer: &str) {
89 lint_suffix_type(key, value, pointer, self.untyped, &mut self.findings);
90 }
91
92 fn number(&mut self, number: &Number, pointer: &str) {
93 if crate::formatting::number_is_integer_literal(number)
94 && !number
95 .as_i64()
96 .is_some_and(|n| n.unsigned_abs() <= MAX_SAFE_INTEGER)
97 {
98 self.findings.push(LintFinding::new(
99 "unsafe_integer",
100 pointer,
101 "integer exceeds JavaScript safe integer range ±(2^53-1)",
102 ));
103 }
104 }
105
106 fn literal(&mut self, name: &str, value: &Value, pointer: &str) {
107 if has_suffix_ci(name, "_secret") && !is_redacted_secret_literal(value) {
108 self.findings.push(LintFinding::new(
109 "secret_schema_value_exposed",
110 pointer,
111 format!("schema property {name:?} exposes a secret literal"),
112 ));
113 }
114 self.field(name, value, pointer);
115 }
116
117 fn property(&mut self, name: &str, schema: &Value, pointer: &str) {
118 lint_schema_suffix_type(name, schema, pointer, &mut self.findings);
119 }
120}
121
122pub fn assert_strict_event(value: &Value) -> Result<(), ProtocolViolation> {
124 validate_protocol_event(value, true)
125}
126
127pub fn assert_no_lint_findings(value: &Value) -> Result<(), Vec<LintFinding>> {
129 let findings = lint_value(value, LintOptions::default());
130 if findings.is_empty() {
131 Ok(())
132 } else {
133 Err(findings)
134 }
135}
136
137#[derive(Clone, Debug, PartialEq, Eq)]
139pub enum RedactionCanaryError {
140 EmptyCanary,
141 Exposed,
143 InspectionLimitExceeded,
146}
147
148impl fmt::Display for RedactionCanaryError {
149 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
150 match self {
151 Self::EmptyCanary => formatter.write_str("redaction canary must not be empty"),
152 Self::Exposed => formatter.write_str("redaction canary remains in serialized output"),
153 Self::InspectionLimitExceeded => formatter.write_str(
154 "serialized output is still encoded after the inspection limit; canary absence is unproven",
155 ),
156 }
157 }
158}
159
160impl std::error::Error for RedactionCanaryError {}
161
162pub fn assert_redaction_canary_absent(
179 serialized: &str,
180 canary: &str,
181) -> Result<(), RedactionCanaryError> {
182 if canary.is_empty() {
183 return Err(RedactionCanaryError::EmptyCanary);
184 }
185 let mut current = std::borrow::Cow::Borrowed(serialized);
186 for _ in 0..64 {
189 if current.contains(canary) {
190 return Err(RedactionCanaryError::Exposed);
191 }
192 let decoded = decode_output_escapes(¤t);
193 if decoded == current {
194 return Ok(());
195 }
196 current = std::borrow::Cow::Owned(decoded);
197 }
198 Err(RedactionCanaryError::InspectionLimitExceeded)
199}
200
201fn decode_output_escapes(text: &str) -> String {
207 let bytes = text.as_bytes();
208 let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
209 let mut index = 0;
210 while index < bytes.len() {
211 match bytes[index] {
212 b'\\' => match decode_backslash_escape(&bytes[index + 1..]) {
213 Some((decoded, consumed)) => {
214 out.extend_from_slice(decoded.as_bytes());
215 index += 1 + consumed;
216 }
217 None => {
218 out.push(bytes[index]);
219 index += 1;
220 }
221 },
222 b'%' => match percent_byte(&bytes[index + 1..]) {
223 Some(byte) => {
224 out.push(byte);
225 index += 3;
226 }
227 None => {
228 out.push(bytes[index]);
229 index += 1;
230 }
231 },
232 other => {
233 out.push(other);
234 index += 1;
235 }
236 }
237 }
238 String::from_utf8_lossy_owned(out)
239}
240
241fn decode_backslash_escape(rest: &[u8]) -> Option<(String, usize)> {
244 let simple = |character: char| Some((character.to_string(), 1));
245 match *rest.first()? {
246 b'n' => simple('\n'),
247 b'r' => simple('\r'),
248 b't' => simple('\t'),
249 b'b' => simple('\u{0008}'),
250 b'f' => simple('\u{000c}'),
251 b'v' => simple('\u{000b}'),
252 b'0' => simple('\0'),
253 b'\\' => simple('\\'),
254 b'"' => simple('"'),
255 b'/' => simple('/'),
256 b'u' => {
257 let first = hex4(rest.get(1..)?)?;
258 if (0xd800..0xdc00).contains(&first) {
261 let low = rest
262 .get(5..7)
263 .filter(|marker| *marker == b"\\u".as_slice())
264 .and_then(|_| rest.get(7..))
265 .and_then(hex4)
266 .filter(|value| (0xdc00..0xe000).contains(value))?;
267 let combined = 0x10000 + ((first - 0xd800) << 10) + (low - 0xdc00);
268 return char::from_u32(combined).map(|character| (character.to_string(), 11));
269 }
270 char::from_u32(first).map(|character| (character.to_string(), 5))
271 }
272 _ => None,
273 }
274}
275
276fn hex4(bytes: &[u8]) -> Option<u32> {
277 let digits = bytes.get(..4)?;
278 std::str::from_utf8(digits)
279 .ok()
280 .and_then(|text| u32::from_str_radix(text, 16).ok())
281}
282
283fn percent_byte(rest: &[u8]) -> Option<u8> {
284 let digits = rest.get(..2)?;
285 std::str::from_utf8(digits)
286 .ok()
287 .and_then(|text| u8::from_str_radix(text, 16).ok())
288}
289
290fn lint_schema_suffix_type(
291 name: &str,
292 schema: &Value,
293 pointer: &str,
294 findings: &mut Vec<LintFinding>,
295) {
296 let has = |suffix| has_suffix_ci(name, suffix);
297 let (types, description): (&[&str], &str) = if has("_bytes") {
298 (&["integer"], "an integer byte count")
299 } else if has("_epoch_s") || has("_epoch_ms") {
300 (&["integer"], "an integer epoch timestamp")
301 } else if has("_epoch_ns") {
302 (&["string"], "a decimal integer string")
303 } else if has("_sats") || has("_msats") {
304 (
305 &["integer", "string"],
306 "an integer or decimal integer string",
307 )
308 } else if has("_percent") || is_duration_suffix(name) {
309 (&["integer", "number"], "a numeric value")
310 } else if is_currency_minor_unit_suffix(name) {
311 (&["integer"], "an integer currency amount")
312 } else if has("_url") {
313 (
314 &["string", "object"],
315 "a URL string or a collection of URLs",
316 )
317 } else if [
318 "_rfc3339",
319 "_bcp47",
320 "_rfc3339_date",
321 "_rfc3339_time",
322 "_utc_offset",
323 ]
324 .iter()
325 .any(|s| has(s))
326 {
327 (&["string"], "a string")
328 } else {
329 return;
330 };
331 if let Some(at) = incompatible_schema(schema, types, pointer, true) {
332 findings.push(LintFinding::new(
333 "suffix_type_mismatch",
334 at,
335 format!("schema property {name:?} must allow {description}"),
336 ));
337 }
338}
339
340fn incompatible_schema(
343 schema: &Value,
344 expected: &[&str],
345 pointer: &str,
346 allow_array: bool,
347) -> Option<String> {
348 let object = schema.as_object()?;
349 if let Some(ty) = object.get("type") {
350 let check = |name: &str| {
351 if name == "array" && allow_array {
352 return object.get("items").and_then(|items| {
353 incompatible_schema(
354 items,
355 expected,
356 &join_pointer(pointer, "items"),
357 expected.contains(&"object"),
358 )
359 });
360 }
361 if expected.contains(&name) || (name == "number" && expected.contains(&"integer")) {
362 None
363 } else {
364 Some(join_pointer(pointer, "type"))
365 }
366 };
367 let conflict = match ty {
368 Value::String(name) => check(name),
369 Value::Array(types)
370 if !types.is_empty()
371 && types.iter().all(|ty| ty.as_str().and_then(check).is_some()) =>
372 {
373 Some(join_pointer(pointer, "type"))
374 }
375 _ => None,
376 };
377 if conflict.is_some() {
378 return conflict;
379 }
380 }
381 for keyword in ["anyOf", "oneOf", "allOf"] {
382 if let Some(Value::Array(branches)) = object.get(keyword) {
383 let at = join_pointer(pointer, keyword);
384 let mut conflicts = branches.iter().enumerate().map(|(i, branch)| {
385 incompatible_schema(branch, expected, &format!("{at}/{i}"), allow_array)
386 });
387 if keyword == "allOf" {
388 if let Some(conflict) = conflicts.find_map(|c| c) {
389 return Some(conflict);
390 }
391 } else if conflicts.all(|c| c.is_some()) {
392 return Some(at);
393 }
394 }
395 }
396 None
397}
398
399fn is_redacted_secret_literal(value: &Value) -> bool {
400 matches!(value, Value::Null) || matches!(value, Value::String(text) if text == "***")
401}
402
403fn is_numeric_suffix(key: &str) -> bool {
404 let has = |suffix: &str| has_suffix_ci(key, suffix);
405 has("_bytes")
406 || has("_epoch_s")
407 || has("_epoch_ms")
408 || has("_sats")
409 || has("_msats")
410 || has("_percent")
411 || is_duration_suffix(key)
412 || is_currency_minor_unit_suffix(key)
413}
414
415fn lint_suffix_scalar_message(key: &str, value: &Value) -> Option<String> {
416 let has = |suffix: &str| has_suffix_ci(key, suffix);
421 if has("_bytes") {
422 (!is_non_negative_integer(value))
423 .then(|| format!("{key:?} must be a non-negative integer byte count"))
424 } else if has("_epoch_s") || has("_epoch_ms") {
425 (!is_integer(value)).then(|| format!("{key:?} must be an integer epoch timestamp"))
426 } else if has("_epoch_ns") {
427 (!is_decimal_integer_string(value))
428 .then(|| format!("{key:?} must be a decimal integer string"))
429 } else if has("_sats") || has("_msats") {
430 (!(is_integer(value) || is_decimal_integer_string(value)))
431 .then(|| format!("{key:?} must be an integer or decimal integer string"))
432 } else if has("_percent") {
433 (!value.is_number()).then(|| format!("{key:?} must be numeric"))
434 } else if is_duration_suffix(key) {
435 (!value.is_number()).then(|| format!("{key:?} must be a numeric duration"))
436 } else if is_currency_minor_unit_suffix(key) {
437 (!is_integer(value)).then(|| format!("{key:?} must be an integer currency amount"))
438 } else if has("_rfc3339") {
439 if value.as_str().is_some_and(is_valid_rfc3339) {
440 None
441 } else if value.is_string() {
442 Some(format!(
443 "{key:?} must be an RFC 3339 date-time with a mandatory offset (e.g. \
444 2026-02-14T10:30:00Z)"
445 ))
446 } else {
447 Some(format!("{key:?} must be a string"))
448 }
449 } else if has("_bcp47") {
450 if value.as_str().is_some_and(is_valid_bcp47) {
451 None
452 } else if value.is_string() {
453 Some(format!("{key:?} must be a well-formed BCP 47 language tag"))
454 } else {
455 Some(format!("{key:?} must be a string"))
456 }
457 } else if has("_rfc3339_date") {
458 if value.as_str().is_some_and(is_valid_rfc3339_date) {
459 None
460 } else if value.is_string() {
461 Some(format!(
462 "{key:?} must be an RFC 3339 full-date (YYYY-MM-DD)"
463 ))
464 } else {
465 Some(format!("{key:?} must be a string"))
466 }
467 } else if has("_rfc3339_time") {
468 if value.as_str().is_some_and(is_valid_rfc3339_time) {
469 None
470 } else if value.is_string() {
471 Some(format!(
472 "{key:?} must be an RFC 3339 partial-time (HH:MM:SS[.fraction], no Z or offset)"
473 ))
474 } else {
475 Some(format!("{key:?} must be a string"))
476 }
477 } else if has("_utc_offset") {
478 if value.as_str().and_then(normalize_utc_offset).is_some() {
479 None
480 } else if value.is_string() {
481 Some(format!(
482 "{key:?} must be a fixed UTC offset (\"UTC\" or ±HH:MM)"
483 ))
484 } else {
485 Some(format!("{key:?} must be a string"))
486 }
487 } else {
488 None
489 }
490}
491
492fn lint_suffix_type(
493 key: &str,
494 value: &Value,
495 pointer: &str,
496 untyped_text_scalars: bool,
497 findings: &mut Vec<LintFinding>,
498) {
499 if value.is_null() || !has_registered_suffix(key) || has_suffix_ci(key, "_secret") {
500 return;
501 }
502 if has_suffix_ci(key, "_url") {
503 let message = match url_field_violation(value) {
507 UrlFieldCheck::Ok => None,
508 UrlFieldCheck::NotAUrl => Some(format!(
509 "{key:?} must be a single URL (invalid URL spelling)"
510 )),
511 UrlFieldCheck::NotAString => Some(format!(
512 "{key:?} must be a URL string, or a collection whose leaves are URL strings"
513 )),
514 };
515 if let Some(message) = message {
516 findings.push(LintFinding::new(
517 "suffix_type_mismatch",
518 pointer.to_string(),
519 message,
520 ));
521 }
522 return;
523 }
524 if let Some(items) = value.as_array() {
525 for (idx, item) in items.iter().enumerate() {
526 if item.is_null() {
527 continue;
528 }
529 let item_pointer = format!("{pointer}/{idx}");
530 let message = if item.is_array() {
531 Some(format!("{key:?} array elements must be scalar values"))
532 } else {
533 scalar_message(key, item, untyped_text_scalars)
534 };
535 if let Some(message) = message {
536 findings.push(LintFinding::new(
537 "suffix_type_mismatch",
538 item_pointer,
539 message,
540 ));
541 }
542 }
543 return;
544 }
545 if let Some(message) = scalar_message(key, value, untyped_text_scalars) {
546 findings.push(LintFinding::new(
547 "suffix_type_mismatch",
548 pointer.to_string(),
549 message,
550 ));
551 }
552}
553
554fn scalar_message(key: &str, value: &Value, untyped: bool) -> Option<String> {
555 if untyped
556 && let Some(text) = value.as_str()
557 && is_numeric_suffix(key)
558 {
559 if text.is_empty() {
560 return None;
561 }
562 return match parse_json_number_text(text) {
563 Some(number) => lint_suffix_scalar_message(key, &number),
564 None => Some(format!("{key:?} must be a decimal numeric text value")),
565 };
566 }
567 lint_suffix_scalar_message(key, value)
568}
569
570fn is_integer(value: &Value) -> bool {
571 matches!(value, Value::Number(number) if number_is_integer(number))
572}
573
574fn is_non_negative_integer(value: &Value) -> bool {
575 let Value::Number(number) = value else {
576 return false;
577 };
578 if !number_is_integer(number) {
579 return false;
580 }
581 let text = number.to_string();
582 !text.starts_with('-') || decimal_number_is_zero(&text)
583}
584
585fn number_is_integer(number: &Number) -> bool {
591 decimal_number_is_integer(&number.to_string())
592}
593
594fn decimal_number_is_integer(text: &str) -> bool {
595 let unsigned = text.trim_prefix('-');
596 let exponent_index = unsigned.find(['e', 'E']);
597 let (mantissa, exponent_text) = exponent_index.map_or((unsigned, None), |index| {
598 (&unsigned[..index], Some(&unsigned[index + 1..]))
599 });
600 if mantissa
601 .bytes()
602 .filter(|byte| *byte != b'.')
603 .all(|byte| byte == b'0')
604 {
605 return true;
606 }
607
608 let fraction_digits = mantissa
609 .split_once('.')
610 .map_or(0, |(_, fraction)| fraction.len());
611 let exponent = exponent_text.map_or(0, |value| {
612 value.parse::<i128>().unwrap_or_else(|_| {
613 if value.starts_with('-') {
614 i128::MIN
615 } else {
616 i128::MAX
617 }
618 })
619 });
620 let scale = exponent.saturating_sub(i128::try_from(fraction_digits).unwrap_or(i128::MAX));
621 if scale >= 0 {
622 return true;
623 }
624
625 let required_trailing_zeroes = scale.unsigned_abs();
626 let digit_count = mantissa.bytes().filter(|byte| *byte != b'.').count();
627 if required_trailing_zeroes > digit_count as u128 {
628 return false;
629 }
630 mantissa
631 .bytes()
632 .filter(|byte| *byte != b'.')
633 .rev()
634 .take(required_trailing_zeroes as usize)
635 .all(|byte| byte == b'0')
636}
637
638fn decimal_number_is_zero(text: &str) -> bool {
639 let unsigned = text.trim_prefix('-');
640 let mantissa = unsigned
641 .split_once(['e', 'E'])
642 .map_or(unsigned, |(mantissa, _)| mantissa);
643 mantissa
644 .bytes()
645 .filter(|byte| *byte != b'.')
646 .all(|byte| byte == b'0')
647}
648
649fn is_decimal_integer_string(value: &Value) -> bool {
650 let Value::String(text) = value else {
651 return false;
652 };
653 let digits = text.trim_prefix('-');
654 !digits.is_empty() && digits.chars().all(|character| character.is_ascii_digit())
655}
656
657fn is_duration_suffix(key: &str) -> bool {
658 ["_ns", "_us", "_ms", "_s", "_minutes", "_hours", "_days"]
659 .iter()
660 .any(|suffix| has_suffix_ci(key, suffix))
661}
662
663fn is_currency_minor_unit_suffix(key: &str) -> bool {
669 currency_code(key, "_cents").is_some()
670 || currency_code(key, "_micro").is_some()
671 || has_suffix_ci(key, "_jpy")
672}
673
674enum UrlFieldCheck {
676 Ok,
677 NotAUrl,
678 NotAString,
679}
680
681fn url_field_violation(value: &Value) -> UrlFieldCheck {
684 match value {
685 Value::Null => UrlFieldCheck::Ok,
686 Value::String(text) => {
687 if crate::redaction::valid_url_field(text) {
688 UrlFieldCheck::Ok
689 } else {
690 UrlFieldCheck::NotAUrl
691 }
692 }
693 Value::Array(items) => first_url_violation(items.iter()),
694 Value::Object(entries) => first_url_violation(
695 entries
696 .iter()
697 .filter(|(key, _)| !has_suffix_ci(key, "_secret"))
698 .map(|(_, value)| value),
699 ),
700 _ => UrlFieldCheck::NotAString,
701 }
702}
703
704fn first_url_violation<'value>(values: impl Iterator<Item = &'value Value>) -> UrlFieldCheck {
705 for value in values {
706 match url_field_violation(value) {
707 UrlFieldCheck::Ok => {}
708 violation => return violation,
709 }
710 }
711 UrlFieldCheck::Ok
712}
713
714#[cfg(test)]
715mod tests {
716 use super::{
717 LintOptions, RedactionCanaryError, assert_no_lint_findings, assert_redaction_canary_absent,
718 assert_strict_event, lint_value,
719 };
720 use crate::suffix::REGISTERED_SUFFIXES;
721 use serde_json::{Value, json};
722
723 #[test]
724 fn assertions_return_only_contract_violations() {
725 let options = LintOptions::default();
726 let legal = json!({"build": "8165", "rows": "1,200", "timeout": 5});
727 assert_no_lint_findings(&legal).unwrap();
728 for (key, value) in legal.as_object().unwrap() {
729 assert!(super::lint_field_value(key, value, options).is_empty());
730 }
731
732 let mixed = json!({"rows": "1,200", "x~/size_bytes": [0, "8 MB"], "when_rfc3339": "today"});
733 let violations = assert_no_lint_findings(&mixed).unwrap_err();
734 assert_eq!(violations, lint_value(&mixed, options));
735 assert_eq!(violations.len(), 2);
736 for (pointer, finding) in ["/when_rfc3339", "/x~0~1size_bytes/1"]
737 .into_iter()
738 .zip(&violations)
739 {
740 assert_eq!(finding.pointer, pointer);
741 assert_eq!(finding.rule_id, "suffix_type_mismatch");
742 assert_eq!(
743 serde_json::to_value(finding).unwrap(),
744 json!({
745 "rule_id": finding.rule_id, "pointer": pointer, "message": finding.message,
746 })
747 );
748 }
749 for (value, pointer) in [(json!("8 MB"), ""), (json!([12, "8 MB"]), "/1")] {
750 let findings = super::lint_field_value("total_bytes", &value, options);
751 assert_eq!(findings.len(), 1);
752 assert_eq!(findings[0].pointer, pointer);
753 }
754 }
755
756 #[test]
757 fn only_integer_literals_outside_the_portable_range_fail() {
758 let values = serde_json::from_str(
759 r#"[-9007199254740991,9007199254740991,-9007199254740992,9007199254740992,9007199254740992.0,1e19,"9007199254740992"]"#,
760 ).unwrap();
761 let findings = assert_no_lint_findings(&values).unwrap_err();
762 assert_eq!(
763 findings
764 .iter()
765 .map(|f| (f.rule_id.as_str(), f.pointer.as_str()))
766 .collect::<Vec<_>>(),
767 [("unsafe_integer", "/2"), ("unsafe_integer", "/3")]
768 );
769 }
770
771 #[test]
772 fn schema_declarations_and_instances_have_distinct_roles() {
773 let schema = LintOptions::new().schema_properties();
774 let literal = json!({"properties":{"option_secret":{"default":"canary"}}});
775 assert_no_lint_findings(&literal).unwrap();
776 let findings = lint_value(&literal, schema);
777 assert_eq!(findings.len(), 1);
778 assert_eq!(findings[0].pointer, "/properties/option_secret/default");
779 assert!(!findings[0].message.contains("canary"));
780
781 let declarations = json!({"properties":{
782 "size_bytes":{"type":"number"}, "size_bYtEs":{"type":"string"},
783 "value_Secret":{"example":42}, "LINKS_URL":{"type":["object","array"],"items":{"type":"string"}},
784 }});
785 assert!(lint_value(&declarations, schema).is_empty());
786 assert!(assert_no_lint_findings(&declarations).is_err());
787 let nested = json!({"$defs":{"properties":{"properties":{
788 "sample":{"default":literal, "example":{"properties":{"size_bytes":{"type":"integer"}}}},
789 "bad_ms":{"allOf":[{"type":"array","items":{"type":"string"}}]},
790 }}}});
791 let errors = lint_value(&nested, schema);
792 let pointers: Vec<_> = errors.iter().map(|f| f.pointer.as_str()).collect();
793 assert_eq!(
794 pointers,
795 [
796 "/$defs/properties/properties/bad_ms/allOf/0/items/type",
797 "/$defs/properties/properties/sample/example/properties/size_bytes"
798 ]
799 );
800 }
801
802 #[test]
803 fn schema_const_and_enum_protect_secrets() {
804 let options = LintOptions::new().schema_properties();
805 let schema = json!({"properties": {
806 "api_key_secret": {"type": "string", "const": "sample", "enum": [null, "***", "sample"]}
807 }});
808 let findings = lint_value(&schema, options);
809 assert_eq!(
810 findings
811 .iter()
812 .map(|item| item.pointer.as_str())
813 .collect::<Vec<_>>(),
814 [
815 "/properties/api_key_secret/const",
816 "/properties/api_key_secret/enum/2"
817 ]
818 );
819 assert!(
820 findings
821 .iter()
822 .all(|item| item.rule_id == "secret_schema_value_exposed")
823 );
824 let redacted = json!({"properties": {
825 "api_key_secret": {"type": "string", "const": "***", "enum": [null, "***"]}
826 }});
827 assert!(lint_value(&redacted, options).is_empty());
828 }
829
830 #[test]
831 fn untyped_input_applies_to_data_inside_schema_documents() {
832 let options = LintOptions::new()
833 .schema_properties()
834 .untyped_text_scalars(true);
835 let value = json!({"properties": {
836 "bad_ms": {"type":"string"},
837 "retry_ms": ["5000", "", null, "5s"],
838 "size_bytes": {"example":"1024"},
839 "sample": {"example":{"properties":{"size_bytes":"1024"}}},
840 }});
841 let errors = lint_value(&value, options);
842 assert_eq!(
843 errors
844 .iter()
845 .map(|f| f.pointer.as_str())
846 .collect::<Vec<_>>(),
847 ["/properties/bad_ms/type", "/properties/retry_ms/3"]
848 );
849 }
850
851 #[test]
852 fn url_shape_matches_redaction_at_collection_leaves() {
853 let good =
854 json!({"links_url":[{"token_secret":42, "next":"/cb"}, " https://example.org/ "]});
855 assert_no_lint_findings(&good).unwrap();
856 for bad in [
857 "prefix=https://host/",
858 "user@host",
859 "two paths",
860 "https://a\u{000b}b",
861 ] {
862 assert!(assert_no_lint_findings(&json!({"links_url":[bad]})).is_err());
863 }
864 }
865
866 #[test]
867 fn integer_suffixes_accept_integral_decimals_and_signed_currency() {
868 let value: Value = serde_json::from_str(
869 r#"{
870 "price_usd_cents": -1,
871 "refund_eur_cents": -3.0,
872 "size_bytes": 3.0,
873 "created_epoch_ms": 3e0
874 }"#,
875 )
876 .unwrap_or_else(|error| panic!("{error}"));
877
878 assert!(lint_value(&value, LintOptions::default()).is_empty());
879 }
880
881 #[test]
882 fn registered_currency_suffixes_accept_three_or_four_letter_codes() {
883 assert!(super::has_registered_suffix("fare_thb_cents"));
884 assert!(super::has_registered_suffix("deposit_usdt_cents"));
885 assert!(!super::has_registered_suffix("total_amount_cents"));
886 assert!(!super::has_registered_suffix("price_usdtx_cents"));
887 }
888
889 #[test]
890 fn integer_suffixes_reject_fractional_values_and_negative_bytes() {
891 let value: Value = serde_json::from_str(
892 r#"{
893 "price_usd_cents": 3.5,
894 "size_bytes": -1
895 }"#,
896 )
897 .unwrap_or_else(|error| panic!("{error}"));
898 let findings = lint_value(&value, LintOptions::default());
899
900 assert_eq!(
901 findings
902 .iter()
903 .filter(|finding| finding.rule_id == "suffix_type_mismatch")
904 .count(),
905 2
906 );
907 }
908
909 #[test]
910 fn unsafe_integer_finds_values_beyond_u128() {
911 let value: Value =
912 serde_json::from_str(r#"{"huge_count":340282366920938463463374607431768211456}"#)
913 .unwrap_or_else(|error| panic!("{error}"));
914 let findings = lint_value(&value, LintOptions::default());
915
916 assert!(
917 findings
918 .iter()
919 .any(|finding| finding.rule_id == "unsafe_integer"),
920 "{findings:?}"
921 );
922 }
923
924 #[test]
925 fn assertion_helpers_cover_protocol_lint_and_redaction() {
926 let event = json!({
927 "kind": "result",
928 "result": {"code": "ready"},
929 "trace": {}
930 });
931 assert!(assert_strict_event(&event).is_ok());
932 assert!(assert_no_lint_findings(&event).is_ok());
933 assert!(assert_redaction_canary_absent("{\"secret\":\"***\"}", "canary-42").is_ok());
934 assert_eq!(
935 assert_redaction_canary_absent("contains canary-42", "canary-42"),
936 Err(RedactionCanaryError::Exposed)
937 );
938 }
939
940 #[test]
944 fn redaction_canary_survives_every_output_escape() {
945 for (label, canary) in [
946 (
947 "pem newlines",
948 "-----BEGIN KEY-----\nabc\n-----END KEY-----",
949 ),
950 ("double quote", "p@ss\"word"),
951 ("backslash path", "C:\\Users\\me\\key"),
952 ("tab", "a\tb"),
953 ("non-bmp", "k\u{1f511}ey"),
954 ] {
955 let rendered = crate::render(
956 &json!({ "note": canary }),
957 crate::OutputFormat::Json,
958 &crate::OutputOptions::default(),
959 );
960 assert!(
961 rendered.contains("note"),
962 "{label}: expected the field to survive rendering"
963 );
964 assert_eq!(
965 assert_redaction_canary_absent(&rendered, canary),
966 Err(RedactionCanaryError::Exposed),
967 "{label}: escaped canary must still be reported, output was {rendered}"
968 );
969 }
970 }
971
972 #[test]
975 fn redaction_canary_is_found_percent_encoded() {
976 assert_eq!(
977 assert_redaction_canary_absent("{\"note\":\"https://h/p?q=a%20b%20c\"}", "a b c"),
978 Err(RedactionCanaryError::Exposed)
979 );
980 }
981
982 #[test]
983 fn redaction_canary_is_found_through_nested_and_mixed_encoding() {
984 for serialized in [
985 r#"{"note":"https://h/?next=https%3A%2F%2Fb%2F%3Fq%3D%2573ecret"}"#,
986 r#"{"note":"\u002573ecret"}"#,
987 r#"{"note":"%5Cu0073ecret"}"#,
988 r#"{"note":"%255CuD83D%255CuDD11"}"#,
989 ] {
990 let canary = if serialized.contains("D83D") {
991 "🔑"
992 } else {
993 "secret"
994 };
995 assert_eq!(
996 assert_redaction_canary_absent(serialized, canary),
997 Err(RedactionCanaryError::Exposed),
998 "encoded output must still report the canary: {serialized}"
999 );
1000 }
1001 assert_eq!(
1002 assert_redaction_canary_absent("%25not-a-canary", "secret"),
1003 Ok(())
1004 );
1005 }
1006
1007 #[test]
1008 fn redaction_canary_inspection_fails_closed_on_excessive_encoding_depth() {
1009 let ordinary = format!("%{}73afe", "25".repeat(15));
1010 assert_eq!(assert_redaction_canary_absent(&ordinary, "secret"), Ok(()));
1011 let deep = format!("%{}73afe{}", "25".repeat(1000), "x".repeat(4096));
1014 assert_eq!(
1015 assert_redaction_canary_absent(&deep, "secret"),
1016 Err(RedactionCanaryError::InspectionLimitExceeded)
1017 );
1018 }
1019
1020 #[test]
1023 fn redaction_canary_stays_quiet_when_the_value_was_redacted() {
1024 for canary in [
1025 "-----BEGIN KEY-----\nabc\n-----END KEY-----",
1026 "p@ss\"word",
1027 "C:\\Users\\me\\key",
1028 "k\u{1f511}ey",
1029 ] {
1030 for format in [
1031 crate::OutputFormat::Json,
1032 crate::OutputFormat::Yaml,
1033 crate::OutputFormat::Plain,
1034 ] {
1035 let rendered = crate::render(
1036 &json!({ "note_secret": canary }),
1037 format,
1038 &crate::OutputOptions::default(),
1039 );
1040 assert_eq!(
1041 assert_redaction_canary_absent(&rendered, canary),
1042 Ok(()),
1043 "redacted output must not report a leak, output was {rendered}"
1044 );
1045 }
1046 }
1047 }
1048
1049 #[test]
1050 fn registry_suffixes_match_the_lint_table() {
1051 const REGISTRY: &str =
1052 include_str!("../../skills/agent-first-data/references/registry.json");
1053 let registry: Value =
1054 serde_json::from_str(REGISTRY).unwrap_or_else(|error| panic!("{error}"));
1055 let suffixes = registry["suffixes"]
1056 .as_array()
1057 .map(Vec::as_slice)
1058 .unwrap_or(&[]);
1059 let mut from_registry: Vec<(String, String)> = suffixes
1060 .iter()
1061 .filter_map(|entry| {
1062 Some((
1063 entry["category"].as_str()?.to_string(),
1064 entry["suffix"].as_str()?.to_string(),
1065 ))
1066 })
1067 .collect();
1068 let mut from_table: Vec<(String, String)> = REGISTERED_SUFFIXES
1069 .iter()
1070 .flat_map(|(category, suffixes)| {
1071 suffixes
1072 .iter()
1073 .map(move |suffix| ((*category).to_string(), (*suffix).to_string()))
1074 })
1075 .collect();
1076 from_registry.sort();
1077 from_table.sort();
1078 assert_eq!(from_table, from_registry);
1079 }
1080}