use crate::lint_input::{Visitor, join_pointer, parse_json_number_text, walk};
use crate::suffix::{currency_code, has_registered_suffix, has_suffix_ci};
use crate::{
ProtocolViolation, is_valid_bcp47, is_valid_rfc3339, is_valid_rfc3339_date,
is_valid_rfc3339_time, normalize_utc_offset, validate_protocol_event,
};
use serde::Serialize;
use serde_json::{Number, Value};
use std::fmt;
const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
pub struct LintFinding {
pub rule_id: String,
pub pointer: String,
pub message: String,
}
impl LintFinding {
fn new(rule_id: &str, pointer: impl Into<String>, message: impl Into<String>) -> Self {
Self {
rule_id: rule_id.to_owned(),
pointer: pointer.into(),
message: message.into(),
}
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct LintOptions {
untyped_text_scalars: bool,
schema_properties: bool,
}
impl LintOptions {
pub const fn new() -> Self {
Self {
untyped_text_scalars: false,
schema_properties: false,
}
}
pub const fn untyped_text_scalars(mut self, untyped_text_scalars: bool) -> Self {
self.untyped_text_scalars = untyped_text_scalars;
self
}
pub const fn schema_properties(mut self) -> Self {
self.schema_properties = true;
self
}
}
pub fn lint_value(value: &Value, options: LintOptions) -> Vec<LintFinding> {
lint_value_with_key(value, None, options)
}
pub fn lint_field_value(key: &str, value: &Value, options: LintOptions) -> Vec<LintFinding> {
lint_value_with_key(value, Some(key), options)
}
fn lint_value_with_key(value: &Value, key: Option<&str>, options: LintOptions) -> Vec<LintFinding> {
let mut checks = ContractChecks {
untyped: options.untyped_text_scalars,
findings: Vec::new(),
};
walk(&mut checks, value, key, "", options.schema_properties);
checks.findings
}
struct ContractChecks {
untyped: bool,
findings: Vec<LintFinding>,
}
impl Visitor for ContractChecks {
fn field(&mut self, key: &str, value: &Value, pointer: &str) {
lint_suffix_type(key, value, pointer, self.untyped, &mut self.findings);
}
fn number(&mut self, number: &Number, pointer: &str) {
if crate::formatting::number_is_integer_literal(number)
&& !number
.as_i64()
.is_some_and(|n| n.unsigned_abs() <= MAX_SAFE_INTEGER)
{
self.findings.push(LintFinding::new(
"unsafe_integer",
pointer,
"integer exceeds JavaScript safe integer range ±(2^53-1)",
));
}
}
fn literal(&mut self, name: &str, value: &Value, pointer: &str) {
if has_suffix_ci(name, "_secret") && !is_redacted_secret_literal(value) {
self.findings.push(LintFinding::new(
"secret_schema_value_exposed",
pointer,
format!("schema property {name:?} exposes a secret literal"),
));
}
self.field(name, value, pointer);
}
fn property(&mut self, name: &str, schema: &Value, pointer: &str) {
lint_schema_suffix_type(name, schema, pointer, &mut self.findings);
}
}
pub fn assert_strict_event(value: &Value) -> Result<(), ProtocolViolation> {
validate_protocol_event(value, true)
}
pub fn assert_no_lint_findings(value: &Value) -> Result<(), Vec<LintFinding>> {
let findings = lint_value(value, LintOptions::default());
if findings.is_empty() {
Ok(())
} else {
Err(findings)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RedactionCanaryError {
EmptyCanary,
Exposed,
InspectionLimitExceeded,
}
impl fmt::Display for RedactionCanaryError {
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::EmptyCanary => formatter.write_str("redaction canary must not be empty"),
Self::Exposed => formatter.write_str("redaction canary remains in serialized output"),
Self::InspectionLimitExceeded => formatter.write_str(
"serialized output is still encoded after the inspection limit; canary absence is unproven",
),
}
}
}
impl std::error::Error for RedactionCanaryError {}
pub fn assert_redaction_canary_absent(
serialized: &str,
canary: &str,
) -> Result<(), RedactionCanaryError> {
if canary.is_empty() {
return Err(RedactionCanaryError::EmptyCanary);
}
let mut current = std::borrow::Cow::Borrowed(serialized);
for _ in 0..64 {
if current.contains(canary) {
return Err(RedactionCanaryError::Exposed);
}
let decoded = decode_output_escapes(¤t);
if decoded == current {
return Ok(());
}
current = std::borrow::Cow::Owned(decoded);
}
Err(RedactionCanaryError::InspectionLimitExceeded)
}
fn decode_output_escapes(text: &str) -> String {
let bytes = text.as_bytes();
let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
let mut index = 0;
while index < bytes.len() {
match bytes[index] {
b'\\' => match decode_backslash_escape(&bytes[index + 1..]) {
Some((decoded, consumed)) => {
out.extend_from_slice(decoded.as_bytes());
index += 1 + consumed;
}
None => {
out.push(bytes[index]);
index += 1;
}
},
b'%' => match percent_byte(&bytes[index + 1..]) {
Some(byte) => {
out.push(byte);
index += 3;
}
None => {
out.push(bytes[index]);
index += 1;
}
},
other => {
out.push(other);
index += 1;
}
}
}
String::from_utf8_lossy_owned(out)
}
fn decode_backslash_escape(rest: &[u8]) -> Option<(String, usize)> {
let simple = |character: char| Some((character.to_string(), 1));
match *rest.first()? {
b'n' => simple('\n'),
b'r' => simple('\r'),
b't' => simple('\t'),
b'b' => simple('\u{0008}'),
b'f' => simple('\u{000c}'),
b'v' => simple('\u{000b}'),
b'0' => simple('\0'),
b'\\' => simple('\\'),
b'"' => simple('"'),
b'/' => simple('/'),
b'u' => {
let first = hex4(rest.get(1..)?)?;
if (0xd800..0xdc00).contains(&first) {
let low = rest
.get(5..7)
.filter(|marker| *marker == b"\\u".as_slice())
.and_then(|_| rest.get(7..))
.and_then(hex4)
.filter(|value| (0xdc00..0xe000).contains(value))?;
let combined = 0x10000 + ((first - 0xd800) << 10) + (low - 0xdc00);
return char::from_u32(combined).map(|character| (character.to_string(), 11));
}
char::from_u32(first).map(|character| (character.to_string(), 5))
}
_ => None,
}
}
fn hex4(bytes: &[u8]) -> Option<u32> {
let digits = bytes.get(..4)?;
std::str::from_utf8(digits)
.ok()
.and_then(|text| u32::from_str_radix(text, 16).ok())
}
fn percent_byte(rest: &[u8]) -> Option<u8> {
let digits = rest.get(..2)?;
std::str::from_utf8(digits)
.ok()
.and_then(|text| u8::from_str_radix(text, 16).ok())
}
fn lint_schema_suffix_type(
name: &str,
schema: &Value,
pointer: &str,
findings: &mut Vec<LintFinding>,
) {
let has = |suffix| has_suffix_ci(name, suffix);
let (types, description): (&[&str], &str) = if has("_bytes") {
(&["integer"], "an integer byte count")
} else if has("_epoch_s") || has("_epoch_ms") {
(&["integer"], "an integer epoch timestamp")
} else if has("_epoch_ns") {
(&["string"], "a decimal integer string")
} else if has("_sats") || has("_msats") {
(
&["integer", "string"],
"an integer or decimal integer string",
)
} else if has("_percent") || is_duration_suffix(name) {
(&["integer", "number"], "a numeric value")
} else if is_currency_minor_unit_suffix(name) {
(&["integer"], "an integer currency amount")
} else if has("_url") {
(
&["string", "object"],
"a URL string or a collection of URLs",
)
} else if [
"_rfc3339",
"_bcp47",
"_rfc3339_date",
"_rfc3339_time",
"_utc_offset",
]
.iter()
.any(|s| has(s))
{
(&["string"], "a string")
} else {
return;
};
if let Some(at) = incompatible_schema(schema, types, pointer, true) {
findings.push(LintFinding::new(
"suffix_type_mismatch",
at,
format!("schema property {name:?} must allow {description}"),
));
}
}
fn incompatible_schema(
schema: &Value,
expected: &[&str],
pointer: &str,
allow_array: bool,
) -> Option<String> {
let object = schema.as_object()?;
if let Some(ty) = object.get("type") {
let check = |name: &str| {
if name == "array" && allow_array {
return object.get("items").and_then(|items| {
incompatible_schema(
items,
expected,
&join_pointer(pointer, "items"),
expected.contains(&"object"),
)
});
}
if expected.contains(&name) || (name == "number" && expected.contains(&"integer")) {
None
} else {
Some(join_pointer(pointer, "type"))
}
};
let conflict = match ty {
Value::String(name) => check(name),
Value::Array(types)
if !types.is_empty()
&& types.iter().all(|ty| ty.as_str().and_then(check).is_some()) =>
{
Some(join_pointer(pointer, "type"))
}
_ => None,
};
if conflict.is_some() {
return conflict;
}
}
for keyword in ["anyOf", "oneOf", "allOf"] {
if let Some(Value::Array(branches)) = object.get(keyword) {
let at = join_pointer(pointer, keyword);
let mut conflicts = branches.iter().enumerate().map(|(i, branch)| {
incompatible_schema(branch, expected, &format!("{at}/{i}"), allow_array)
});
if keyword == "allOf" {
if let Some(conflict) = conflicts.find_map(|c| c) {
return Some(conflict);
}
} else if conflicts.all(|c| c.is_some()) {
return Some(at);
}
}
}
None
}
fn is_redacted_secret_literal(value: &Value) -> bool {
matches!(value, Value::Null) || matches!(value, Value::String(text) if text == "***")
}
fn is_numeric_suffix(key: &str) -> bool {
let has = |suffix: &str| has_suffix_ci(key, suffix);
has("_bytes")
|| has("_epoch_s")
|| has("_epoch_ms")
|| has("_sats")
|| has("_msats")
|| has("_percent")
|| is_duration_suffix(key)
|| is_currency_minor_unit_suffix(key)
}
fn lint_suffix_scalar_message(key: &str, value: &Value) -> Option<String> {
let has = |suffix: &str| has_suffix_ci(key, suffix);
if has("_bytes") {
(!is_non_negative_integer(value))
.then(|| format!("{key:?} must be a non-negative integer byte count"))
} else if has("_epoch_s") || has("_epoch_ms") {
(!is_integer(value)).then(|| format!("{key:?} must be an integer epoch timestamp"))
} else if has("_epoch_ns") {
(!is_decimal_integer_string(value))
.then(|| format!("{key:?} must be a decimal integer string"))
} else if has("_sats") || has("_msats") {
(!(is_integer(value) || is_decimal_integer_string(value)))
.then(|| format!("{key:?} must be an integer or decimal integer string"))
} else if has("_percent") {
(!value.is_number()).then(|| format!("{key:?} must be numeric"))
} else if is_duration_suffix(key) {
(!value.is_number()).then(|| format!("{key:?} must be a numeric duration"))
} else if is_currency_minor_unit_suffix(key) {
(!is_integer(value)).then(|| format!("{key:?} must be an integer currency amount"))
} else if has("_rfc3339") {
if value.as_str().is_some_and(is_valid_rfc3339) {
None
} else if value.is_string() {
Some(format!(
"{key:?} must be an RFC 3339 date-time with a mandatory offset (e.g. \
2026-02-14T10:30:00Z)"
))
} else {
Some(format!("{key:?} must be a string"))
}
} else if has("_bcp47") {
if value.as_str().is_some_and(is_valid_bcp47) {
None
} else if value.is_string() {
Some(format!("{key:?} must be a well-formed BCP 47 language tag"))
} else {
Some(format!("{key:?} must be a string"))
}
} else if has("_rfc3339_date") {
if value.as_str().is_some_and(is_valid_rfc3339_date) {
None
} else if value.is_string() {
Some(format!(
"{key:?} must be an RFC 3339 full-date (YYYY-MM-DD)"
))
} else {
Some(format!("{key:?} must be a string"))
}
} else if has("_rfc3339_time") {
if value.as_str().is_some_and(is_valid_rfc3339_time) {
None
} else if value.is_string() {
Some(format!(
"{key:?} must be an RFC 3339 partial-time (HH:MM:SS[.fraction], no Z or offset)"
))
} else {
Some(format!("{key:?} must be a string"))
}
} else if has("_utc_offset") {
if value.as_str().and_then(normalize_utc_offset).is_some() {
None
} else if value.is_string() {
Some(format!(
"{key:?} must be a fixed UTC offset (\"UTC\" or ±HH:MM)"
))
} else {
Some(format!("{key:?} must be a string"))
}
} else {
None
}
}
fn lint_suffix_type(
key: &str,
value: &Value,
pointer: &str,
untyped_text_scalars: bool,
findings: &mut Vec<LintFinding>,
) {
if value.is_null() || !has_registered_suffix(key) || has_suffix_ci(key, "_secret") {
return;
}
if has_suffix_ci(key, "_url") {
let message = match url_field_violation(value) {
UrlFieldCheck::Ok => None,
UrlFieldCheck::NotAUrl => Some(format!(
"{key:?} must be a single URL (invalid URL spelling)"
)),
UrlFieldCheck::NotAString => Some(format!(
"{key:?} must be a URL string, or a collection whose leaves are URL strings"
)),
};
if let Some(message) = message {
findings.push(LintFinding::new(
"suffix_type_mismatch",
pointer.to_string(),
message,
));
}
return;
}
if let Some(items) = value.as_array() {
for (idx, item) in items.iter().enumerate() {
if item.is_null() {
continue;
}
let item_pointer = format!("{pointer}/{idx}");
let message = if item.is_array() {
Some(format!("{key:?} array elements must be scalar values"))
} else {
scalar_message(key, item, untyped_text_scalars)
};
if let Some(message) = message {
findings.push(LintFinding::new(
"suffix_type_mismatch",
item_pointer,
message,
));
}
}
return;
}
if let Some(message) = scalar_message(key, value, untyped_text_scalars) {
findings.push(LintFinding::new(
"suffix_type_mismatch",
pointer.to_string(),
message,
));
}
}
fn scalar_message(key: &str, value: &Value, untyped: bool) -> Option<String> {
if untyped
&& let Some(text) = value.as_str()
&& is_numeric_suffix(key)
{
if text.is_empty() {
return None;
}
return match parse_json_number_text(text) {
Some(number) => lint_suffix_scalar_message(key, &number),
None => Some(format!("{key:?} must be a decimal numeric text value")),
};
}
lint_suffix_scalar_message(key, value)
}
fn is_integer(value: &Value) -> bool {
matches!(value, Value::Number(number) if number_is_integer(number))
}
fn is_non_negative_integer(value: &Value) -> bool {
let Value::Number(number) = value else {
return false;
};
if !number_is_integer(number) {
return false;
}
let text = number.to_string();
!text.starts_with('-') || decimal_number_is_zero(&text)
}
fn number_is_integer(number: &Number) -> bool {
decimal_number_is_integer(&number.to_string())
}
fn decimal_number_is_integer(text: &str) -> bool {
let unsigned = text.trim_prefix('-');
let exponent_index = unsigned.find(['e', 'E']);
let (mantissa, exponent_text) = exponent_index.map_or((unsigned, None), |index| {
(&unsigned[..index], Some(&unsigned[index + 1..]))
});
if mantissa
.bytes()
.filter(|byte| *byte != b'.')
.all(|byte| byte == b'0')
{
return true;
}
let fraction_digits = mantissa
.split_once('.')
.map_or(0, |(_, fraction)| fraction.len());
let exponent = exponent_text.map_or(0, |value| {
value.parse::<i128>().unwrap_or_else(|_| {
if value.starts_with('-') {
i128::MIN
} else {
i128::MAX
}
})
});
let scale = exponent.saturating_sub(i128::try_from(fraction_digits).unwrap_or(i128::MAX));
if scale >= 0 {
return true;
}
let required_trailing_zeroes = scale.unsigned_abs();
let digit_count = mantissa.bytes().filter(|byte| *byte != b'.').count();
if required_trailing_zeroes > digit_count as u128 {
return false;
}
mantissa
.bytes()
.filter(|byte| *byte != b'.')
.rev()
.take(required_trailing_zeroes as usize)
.all(|byte| byte == b'0')
}
fn decimal_number_is_zero(text: &str) -> bool {
let unsigned = text.trim_prefix('-');
let mantissa = unsigned
.split_once(['e', 'E'])
.map_or(unsigned, |(mantissa, _)| mantissa);
mantissa
.bytes()
.filter(|byte| *byte != b'.')
.all(|byte| byte == b'0')
}
fn is_decimal_integer_string(value: &Value) -> bool {
let Value::String(text) = value else {
return false;
};
let digits = text.trim_prefix('-');
!digits.is_empty() && digits.chars().all(|character| character.is_ascii_digit())
}
fn is_duration_suffix(key: &str) -> bool {
["_ns", "_us", "_ms", "_s", "_minutes", "_hours", "_days"]
.iter()
.any(|suffix| has_suffix_ci(key, suffix))
}
fn is_currency_minor_unit_suffix(key: &str) -> bool {
currency_code(key, "_cents").is_some()
|| currency_code(key, "_micro").is_some()
|| has_suffix_ci(key, "_jpy")
}
enum UrlFieldCheck {
Ok,
NotAUrl,
NotAString,
}
fn url_field_violation(value: &Value) -> UrlFieldCheck {
match value {
Value::Null => UrlFieldCheck::Ok,
Value::String(text) => {
if crate::redaction::valid_url_field(text) {
UrlFieldCheck::Ok
} else {
UrlFieldCheck::NotAUrl
}
}
Value::Array(items) => first_url_violation(items.iter()),
Value::Object(entries) => first_url_violation(
entries
.iter()
.filter(|(key, _)| !has_suffix_ci(key, "_secret"))
.map(|(_, value)| value),
),
_ => UrlFieldCheck::NotAString,
}
}
fn first_url_violation<'value>(values: impl Iterator<Item = &'value Value>) -> UrlFieldCheck {
for value in values {
match url_field_violation(value) {
UrlFieldCheck::Ok => {}
violation => return violation,
}
}
UrlFieldCheck::Ok
}
#[cfg(test)]
mod tests {
use super::{
LintOptions, RedactionCanaryError, assert_no_lint_findings, assert_redaction_canary_absent,
assert_strict_event, lint_value,
};
use crate::suffix::REGISTERED_SUFFIXES;
use serde_json::{Value, json};
#[test]
fn assertions_return_only_contract_violations() {
let options = LintOptions::default();
let legal = json!({"build": "8165", "rows": "1,200", "timeout": 5});
assert_no_lint_findings(&legal).unwrap();
for (key, value) in legal.as_object().unwrap() {
assert!(super::lint_field_value(key, value, options).is_empty());
}
let mixed = json!({"rows": "1,200", "x~/size_bytes": [0, "8 MB"], "when_rfc3339": "today"});
let violations = assert_no_lint_findings(&mixed).unwrap_err();
assert_eq!(violations, lint_value(&mixed, options));
assert_eq!(violations.len(), 2);
for (pointer, finding) in ["/when_rfc3339", "/x~0~1size_bytes/1"]
.into_iter()
.zip(&violations)
{
assert_eq!(finding.pointer, pointer);
assert_eq!(finding.rule_id, "suffix_type_mismatch");
assert_eq!(
serde_json::to_value(finding).unwrap(),
json!({
"rule_id": finding.rule_id, "pointer": pointer, "message": finding.message,
})
);
}
for (value, pointer) in [(json!("8 MB"), ""), (json!([12, "8 MB"]), "/1")] {
let findings = super::lint_field_value("total_bytes", &value, options);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].pointer, pointer);
}
}
#[test]
fn only_integer_literals_outside_the_portable_range_fail() {
let values = serde_json::from_str(
r#"[-9007199254740991,9007199254740991,-9007199254740992,9007199254740992,9007199254740992.0,1e19,"9007199254740992"]"#,
).unwrap();
let findings = assert_no_lint_findings(&values).unwrap_err();
assert_eq!(
findings
.iter()
.map(|f| (f.rule_id.as_str(), f.pointer.as_str()))
.collect::<Vec<_>>(),
[("unsafe_integer", "/2"), ("unsafe_integer", "/3")]
);
}
#[test]
fn schema_declarations_and_instances_have_distinct_roles() {
let schema = LintOptions::new().schema_properties();
let literal = json!({"properties":{"option_secret":{"default":"canary"}}});
assert_no_lint_findings(&literal).unwrap();
let findings = lint_value(&literal, schema);
assert_eq!(findings.len(), 1);
assert_eq!(findings[0].pointer, "/properties/option_secret/default");
assert!(!findings[0].message.contains("canary"));
let declarations = json!({"properties":{
"size_bytes":{"type":"number"}, "size_bYtEs":{"type":"string"},
"value_Secret":{"example":42}, "LINKS_URL":{"type":["object","array"],"items":{"type":"string"}},
}});
assert!(lint_value(&declarations, schema).is_empty());
assert!(assert_no_lint_findings(&declarations).is_err());
let nested = json!({"$defs":{"properties":{"properties":{
"sample":{"default":literal, "example":{"properties":{"size_bytes":{"type":"integer"}}}},
"bad_ms":{"allOf":[{"type":"array","items":{"type":"string"}}]},
}}}});
let errors = lint_value(&nested, schema);
let pointers: Vec<_> = errors.iter().map(|f| f.pointer.as_str()).collect();
assert_eq!(
pointers,
[
"/$defs/properties/properties/bad_ms/allOf/0/items/type",
"/$defs/properties/properties/sample/example/properties/size_bytes"
]
);
}
#[test]
fn schema_const_and_enum_protect_secrets() {
let options = LintOptions::new().schema_properties();
let schema = json!({"properties": {
"api_key_secret": {"type": "string", "const": "sample", "enum": [null, "***", "sample"]}
}});
let findings = lint_value(&schema, options);
assert_eq!(
findings
.iter()
.map(|item| item.pointer.as_str())
.collect::<Vec<_>>(),
[
"/properties/api_key_secret/const",
"/properties/api_key_secret/enum/2"
]
);
assert!(
findings
.iter()
.all(|item| item.rule_id == "secret_schema_value_exposed")
);
let redacted = json!({"properties": {
"api_key_secret": {"type": "string", "const": "***", "enum": [null, "***"]}
}});
assert!(lint_value(&redacted, options).is_empty());
}
#[test]
fn untyped_input_applies_to_data_inside_schema_documents() {
let options = LintOptions::new()
.schema_properties()
.untyped_text_scalars(true);
let value = json!({"properties": {
"bad_ms": {"type":"string"},
"retry_ms": ["5000", "", null, "5s"],
"size_bytes": {"example":"1024"},
"sample": {"example":{"properties":{"size_bytes":"1024"}}},
}});
let errors = lint_value(&value, options);
assert_eq!(
errors
.iter()
.map(|f| f.pointer.as_str())
.collect::<Vec<_>>(),
["/properties/bad_ms/type", "/properties/retry_ms/3"]
);
}
#[test]
fn url_shape_matches_redaction_at_collection_leaves() {
let good =
json!({"links_url":[{"token_secret":42, "next":"/cb"}, " https://example.org/ "]});
assert_no_lint_findings(&good).unwrap();
for bad in [
"prefix=https://host/",
"user@host",
"two paths",
"https://a\u{000b}b",
] {
assert!(assert_no_lint_findings(&json!({"links_url":[bad]})).is_err());
}
}
#[test]
fn integer_suffixes_accept_integral_decimals_and_signed_currency() {
let value: Value = serde_json::from_str(
r#"{
"price_usd_cents": -1,
"refund_eur_cents": -3.0,
"size_bytes": 3.0,
"created_epoch_ms": 3e0
}"#,
)
.unwrap_or_else(|error| panic!("{error}"));
assert!(lint_value(&value, LintOptions::default()).is_empty());
}
#[test]
fn registered_currency_suffixes_accept_three_or_four_letter_codes() {
assert!(super::has_registered_suffix("fare_thb_cents"));
assert!(super::has_registered_suffix("deposit_usdt_cents"));
assert!(!super::has_registered_suffix("total_amount_cents"));
assert!(!super::has_registered_suffix("price_usdtx_cents"));
}
#[test]
fn integer_suffixes_reject_fractional_values_and_negative_bytes() {
let value: Value = serde_json::from_str(
r#"{
"price_usd_cents": 3.5,
"size_bytes": -1
}"#,
)
.unwrap_or_else(|error| panic!("{error}"));
let findings = lint_value(&value, LintOptions::default());
assert_eq!(
findings
.iter()
.filter(|finding| finding.rule_id == "suffix_type_mismatch")
.count(),
2
);
}
#[test]
fn unsafe_integer_finds_values_beyond_u128() {
let value: Value =
serde_json::from_str(r#"{"huge_count":340282366920938463463374607431768211456}"#)
.unwrap_or_else(|error| panic!("{error}"));
let findings = lint_value(&value, LintOptions::default());
assert!(
findings
.iter()
.any(|finding| finding.rule_id == "unsafe_integer"),
"{findings:?}"
);
}
#[test]
fn assertion_helpers_cover_protocol_lint_and_redaction() {
let event = json!({
"kind": "result",
"result": {"code": "ready"},
"trace": {}
});
assert!(assert_strict_event(&event).is_ok());
assert!(assert_no_lint_findings(&event).is_ok());
assert!(assert_redaction_canary_absent("{\"secret\":\"***\"}", "canary-42").is_ok());
assert_eq!(
assert_redaction_canary_absent("contains canary-42", "canary-42"),
Err(RedactionCanaryError::Exposed)
);
}
#[test]
fn redaction_canary_survives_every_output_escape() {
for (label, canary) in [
(
"pem newlines",
"-----BEGIN KEY-----\nabc\n-----END KEY-----",
),
("double quote", "p@ss\"word"),
("backslash path", "C:\\Users\\me\\key"),
("tab", "a\tb"),
("non-bmp", "k\u{1f511}ey"),
] {
let rendered = crate::render(
&json!({ "note": canary }),
crate::OutputFormat::Json,
&crate::OutputOptions::default(),
);
assert!(
rendered.contains("note"),
"{label}: expected the field to survive rendering"
);
assert_eq!(
assert_redaction_canary_absent(&rendered, canary),
Err(RedactionCanaryError::Exposed),
"{label}: escaped canary must still be reported, output was {rendered}"
);
}
}
#[test]
fn redaction_canary_is_found_percent_encoded() {
assert_eq!(
assert_redaction_canary_absent("{\"note\":\"https://h/p?q=a%20b%20c\"}", "a b c"),
Err(RedactionCanaryError::Exposed)
);
}
#[test]
fn redaction_canary_is_found_through_nested_and_mixed_encoding() {
for serialized in [
r#"{"note":"https://h/?next=https%3A%2F%2Fb%2F%3Fq%3D%2573ecret"}"#,
r#"{"note":"\u002573ecret"}"#,
r#"{"note":"%5Cu0073ecret"}"#,
r#"{"note":"%255CuD83D%255CuDD11"}"#,
] {
let canary = if serialized.contains("D83D") {
"🔑"
} else {
"secret"
};
assert_eq!(
assert_redaction_canary_absent(serialized, canary),
Err(RedactionCanaryError::Exposed),
"encoded output must still report the canary: {serialized}"
);
}
assert_eq!(
assert_redaction_canary_absent("%25not-a-canary", "secret"),
Ok(())
);
}
#[test]
fn redaction_canary_inspection_fails_closed_on_excessive_encoding_depth() {
let ordinary = format!("%{}73afe", "25".repeat(15));
assert_eq!(assert_redaction_canary_absent(&ordinary, "secret"), Ok(()));
let deep = format!("%{}73afe{}", "25".repeat(1000), "x".repeat(4096));
assert_eq!(
assert_redaction_canary_absent(&deep, "secret"),
Err(RedactionCanaryError::InspectionLimitExceeded)
);
}
#[test]
fn redaction_canary_stays_quiet_when_the_value_was_redacted() {
for canary in [
"-----BEGIN KEY-----\nabc\n-----END KEY-----",
"p@ss\"word",
"C:\\Users\\me\\key",
"k\u{1f511}ey",
] {
for format in [
crate::OutputFormat::Json,
crate::OutputFormat::Yaml,
crate::OutputFormat::Plain,
] {
let rendered = crate::render(
&json!({ "note_secret": canary }),
format,
&crate::OutputOptions::default(),
);
assert_eq!(
assert_redaction_canary_absent(&rendered, canary),
Ok(()),
"redacted output must not report a leak, output was {rendered}"
);
}
}
}
#[test]
fn registry_suffixes_match_the_lint_table() {
const REGISTRY: &str =
include_str!("../../skills/agent-first-data/references/registry.json");
let registry: Value =
serde_json::from_str(REGISTRY).unwrap_or_else(|error| panic!("{error}"));
let suffixes = registry["suffixes"]
.as_array()
.map(Vec::as_slice)
.unwrap_or(&[]);
let mut from_registry: Vec<(String, String)> = suffixes
.iter()
.filter_map(|entry| {
Some((
entry["category"].as_str()?.to_string(),
entry["suffix"].as_str()?.to_string(),
))
})
.collect();
let mut from_table: Vec<(String, String)> = REGISTERED_SUFFIXES
.iter()
.flat_map(|(category, suffixes)| {
suffixes
.iter()
.map(move |suffix| ((*category).to_string(), (*suffix).to_string()))
})
.collect();
from_registry.sort();
from_table.sort();
assert_eq!(from_table, from_registry);
}
}