Skip to main content

agent_first_data/
lint.rs

1//! In-process AFDATA naming and serialized-output checks.
2
3use crate::{
4    ProtocolViolation, is_valid_bcp47, is_valid_rfc3339, is_valid_rfc3339_date,
5    is_valid_rfc3339_time, normalize_utc_offset, validate_protocol_event,
6};
7use serde::Serialize;
8use serde_json::{Number, Value};
9use std::fmt;
10
11const MAX_SAFE_INTEGER: u64 = 9_007_199_254_740_991;
12
13/// Finding severity, ordered from advisory to failing.
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Serialize)]
15#[serde(rename_all = "lowercase")]
16pub enum LintSeverity {
17    Warning,
18    Error,
19}
20
21impl LintSeverity {
22    pub const fn as_str(self) -> &'static str {
23        match self {
24            Self::Warning => "warning",
25            Self::Error => "error",
26        }
27    }
28}
29
30impl fmt::Display for LintSeverity {
31    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
32        formatter.write_str(self.as_str())
33    }
34}
35
36/// One deterministic AFDATA lint finding.
37#[derive(Clone, Debug, PartialEq, Eq, Serialize)]
38pub struct LintFinding {
39    pub rule_id: String,
40    pub severity: LintSeverity,
41    pub pointer: String,
42    pub message: String,
43}
44
45impl LintFinding {
46    pub fn error(rule_id: &str, pointer: impl Into<String>, message: impl Into<String>) -> Self {
47        Self {
48            rule_id: rule_id.to_string(),
49            severity: LintSeverity::Error,
50            pointer: pointer.into(),
51            message: message.into(),
52        }
53    }
54
55    pub fn warning(rule_id: &str, pointer: impl Into<String>, message: impl Into<String>) -> Self {
56        Self {
57            rule_id: rule_id.to_string(),
58            severity: LintSeverity::Warning,
59            pointer: pointer.into(),
60            message: message.into(),
61        }
62    }
63
64    pub const fn is_error(&self) -> bool {
65        matches!(self.severity, LintSeverity::Error)
66    }
67
68    pub fn to_json(&self) -> Value {
69        serde_json::json!({
70            "rule_id": self.rule_id,
71            "severity": self.severity,
72            "pointer": self.pointer,
73            "message": self.message,
74        })
75    }
76}
77
78/// Controls which deterministic findings are returned.
79#[derive(Clone, Copy, Debug, PartialEq, Eq)]
80pub struct LintOptions {
81    minimum_severity: LintSeverity,
82    untyped_text_scalars: bool,
83    runtime_values: bool,
84}
85
86impl LintOptions {
87    /// Include warnings and errors.
88    pub const fn new() -> Self {
89        Self {
90            minimum_severity: LintSeverity::Warning,
91            untyped_text_scalars: false,
92            runtime_values: false,
93        }
94    }
95
96    /// Return only findings at or above `minimum_severity`.
97    pub const fn minimum_severity(mut self, minimum_severity: LintSeverity) -> Self {
98        self.minimum_severity = minimum_severity;
99        self
100    }
101
102    /// Treat scalar strings as untyped text (for dotenv and INI).
103    pub const fn untyped_text_scalars(mut self, untyped_text_scalars: bool) -> Self {
104        self.untyped_text_scalars = untyped_text_scalars;
105        self
106    }
107
108    /// Treat all objects as data, including fields named `properties`.
109    pub const fn runtime_values(mut self) -> Self {
110        self.runtime_values = true;
111        self
112    }
113
114    pub const fn errors_only() -> Self {
115        Self::new().minimum_severity(LintSeverity::Error)
116    }
117}
118
119impl Default for LintOptions {
120    fn default() -> Self {
121        Self::new()
122    }
123}
124
125/// Lint an actual serialized JSON value in-process.
126pub fn lint_value(value: &Value, options: LintOptions) -> Vec<LintFinding> {
127    lint_value_with_key(value, None, options)
128}
129
130/// Lint a field value supplied separately from its key, as in a model update.
131/// Findings use JSON pointers relative to the supplied value.
132pub fn lint_field_value(key: &str, value: &Value, options: LintOptions) -> Vec<LintFinding> {
133    lint_value_with_key(value, Some(key), options)
134}
135
136fn lint_value_with_key(value: &Value, key: Option<&str>, options: LintOptions) -> Vec<LintFinding> {
137    let mut findings = Vec::new();
138    if let Some(key) = key {
139        lint_field(key, value, "", options, &mut findings);
140    } else {
141        lint_value_at(value, "", None, options, &mut findings);
142    }
143    findings.retain(|finding| finding.severity >= options.minimum_severity);
144    findings
145}
146
147/// Assert the recommended strict protocol profile without spawning the CLI.
148pub fn assert_strict_event(value: &Value) -> Result<(), ProtocolViolation> {
149    validate_protocol_event(value, true)
150}
151
152/// Return every default lint finding as `Err`; useful in unit tests.
153pub fn assert_no_lint_findings(value: &Value) -> Result<(), Vec<LintFinding>> {
154    assert_no_lint_findings_with_options(value, LintOptions::default())
155}
156
157/// As [`assert_no_lint_findings`], with explicit severity filtering.
158pub fn assert_no_lint_findings_with_options(
159    value: &Value,
160    options: LintOptions,
161) -> Result<(), Vec<LintFinding>> {
162    let findings = lint_value(value, options);
163    if findings.is_empty() {
164        Ok(())
165    } else {
166        Err(findings)
167    }
168}
169
170/// Failure from [`assert_redaction_canary_absent`].
171#[derive(Clone, Debug, PartialEq, Eq)]
172pub enum RedactionCanaryError {
173    EmptyCanary,
174    /// The canary is present in the output or in one of its decoded layers.
175    Exposed,
176    /// Layered encoding was still changing when the decoding budget ran out,
177    /// so absence could not be shown. A failure, but not a confirmed leak.
178    InspectionLimitExceeded,
179}
180
181impl fmt::Display for RedactionCanaryError {
182    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
183        match self {
184            Self::EmptyCanary => formatter.write_str("redaction canary must not be empty"),
185            Self::Exposed => formatter.write_str("redaction canary remains in serialized output"),
186            Self::InspectionLimitExceeded => formatter.write_str(
187                "serialized output is still encoded after the inspection limit; canary absence is unproven",
188            ),
189        }
190    }
191}
192
193impl std::error::Error for RedactionCanaryError {}
194
195/// Verify that a unique test canary is absent from final serialized output.
196///
197/// Pass the string returned by [`crate::render`] or an HTTP/body serializer,
198/// not the pre-redaction input value.
199///
200/// Every renderer escapes a string before it reaches the stream, so a canary
201/// can be present verbatim yet unfindable by a raw substring search: a PEM key
202/// carries newlines, a password may carry `"`, a Windows path carries `\`, and
203/// a canary inside a `_url` value is percent-encoded. This checks the raw text
204/// *and* decoded copies until no escapes change, so nested URL encoding and
205/// serialization escapes cannot hide a leak. Decoding the haystack rather than
206/// enumerating the escaped spellings of the canary keeps the check from
207/// drifting when a renderer changes, and biases it the safe way: an over-eager
208/// decode can only raise a false alarm, never pass a real leak. Inspection is
209/// bounded to 64 decoding passes; encoding that still changes at that bound
210/// fails closed as [`RedactionCanaryError::InspectionLimitExceeded`].
211pub fn assert_redaction_canary_absent(
212    serialized: &str,
213    canary: &str,
214) -> Result<(), RedactionCanaryError> {
215    if canary.is_empty() {
216        return Err(RedactionCanaryError::EmptyCanary);
217    }
218    let mut current = std::borrow::Cow::Borrowed(serialized);
219    // Deep percent chains otherwise remove only two bytes per full scan,
220    // making a small encoded prefix plus a large body quadratic to inspect.
221    for _ in 0..64 {
222        if current.contains(canary) {
223            return Err(RedactionCanaryError::Exposed);
224        }
225        let decoded = decode_output_escapes(&current);
226        if decoded == current {
227            return Ok(());
228        }
229        current = std::borrow::Cow::Owned(decoded);
230    }
231    Err(RedactionCanaryError::InspectionLimitExceeded)
232}
233
234/// Undo every escape AFDATA output can introduce: JSON and YAML string escapes,
235/// logfmt quoting, and percent-encoding inside a URL.
236///
237/// Only used to widen the canary search, so an unrecognized escape is left
238/// alone rather than guessed at.
239fn decode_output_escapes(text: &str) -> String {
240    let bytes = text.as_bytes();
241    let mut out: Vec<u8> = Vec::with_capacity(bytes.len());
242    let mut index = 0;
243    while index < bytes.len() {
244        match bytes[index] {
245            b'\\' => match decode_backslash_escape(&bytes[index + 1..]) {
246                Some((decoded, consumed)) => {
247                    out.extend_from_slice(decoded.as_bytes());
248                    index += 1 + consumed;
249                }
250                None => {
251                    out.push(bytes[index]);
252                    index += 1;
253                }
254            },
255            b'%' => match percent_byte(&bytes[index + 1..]) {
256                Some(byte) => {
257                    out.push(byte);
258                    index += 3;
259                }
260                None => {
261                    out.push(bytes[index]);
262                    index += 1;
263                }
264            },
265            other => {
266                out.push(other);
267                index += 1;
268            }
269        }
270    }
271    String::from_utf8_lossy_owned(out)
272}
273
274/// Decode one escape body (the bytes after a `\`), returning it with the number
275/// of bytes consumed.
276fn decode_backslash_escape(rest: &[u8]) -> Option<(String, usize)> {
277    let simple = |character: char| Some((character.to_string(), 1));
278    match *rest.first()? {
279        b'n' => simple('\n'),
280        b'r' => simple('\r'),
281        b't' => simple('\t'),
282        b'b' => simple('\u{0008}'),
283        b'f' => simple('\u{000c}'),
284        b'v' => simple('\u{000b}'),
285        b'0' => simple('\0'),
286        b'\\' => simple('\\'),
287        b'"' => simple('"'),
288        b'/' => simple('/'),
289        b'u' => {
290            let first = hex4(rest.get(1..)?)?;
291            // A non-BMP character is escaped as a surrogate pair; decoding the
292            // halves separately would lose the character entirely.
293            if (0xd800..0xdc00).contains(&first) {
294                let low = rest
295                    .get(5..7)
296                    .filter(|marker| *marker == b"\\u".as_slice())
297                    .and_then(|_| rest.get(7..))
298                    .and_then(hex4)
299                    .filter(|value| (0xdc00..0xe000).contains(value))?;
300                let combined = 0x10000 + ((first - 0xd800) << 10) + (low - 0xdc00);
301                return char::from_u32(combined).map(|character| (character.to_string(), 11));
302            }
303            char::from_u32(first).map(|character| (character.to_string(), 5))
304        }
305        _ => None,
306    }
307}
308
309fn hex4(bytes: &[u8]) -> Option<u32> {
310    let digits = bytes.get(..4)?;
311    std::str::from_utf8(digits)
312        .ok()
313        .and_then(|text| u32::from_str_radix(text, 16).ok())
314}
315
316fn percent_byte(rest: &[u8]) -> Option<u8> {
317    let digits = rest.get(..2)?;
318    std::str::from_utf8(digits)
319        .ok()
320        .and_then(|text| u8::from_str_radix(text, 16).ok())
321}
322
323fn lint_value_at(
324    value: &Value,
325    pointer: &str,
326    key: Option<&str>,
327    options: LintOptions,
328    findings: &mut Vec<LintFinding>,
329) {
330    lint_unsafe_integer(value, pointer, findings);
331    if options.minimum_severity == LintSeverity::Warning
332        && !options.untyped_text_scalars
333        && let Some(text) = value.as_str()
334    {
335        lint_formatted_quantity(key, text, pointer, findings);
336    }
337    match value {
338        Value::Object(map) => {
339            if !options.runtime_values
340                && let Some(Value::Object(properties)) = map.get("properties")
341            {
342                for (name, schema) in properties {
343                    lint_schema_property(
344                        name,
345                        schema,
346                        &join_pointer(pointer, "properties"),
347                        options,
348                        findings,
349                    );
350                }
351            }
352            for (key, child) in map {
353                // JSON Schema property descriptors are not runtime values.
354                if !options.runtime_values && key == "properties" && child.is_object() {
355                    continue;
356                }
357                let child_pointer = join_pointer(pointer, key);
358                lint_field(key, child, &child_pointer, options, findings);
359            }
360        }
361        Value::Array(items) => {
362            for (index, item) in items.iter().enumerate() {
363                lint_value_at(
364                    item,
365                    &join_pointer(pointer, &index.to_string()),
366                    key,
367                    options,
368                    findings,
369                );
370            }
371        }
372        _ => {}
373    }
374}
375
376fn lint_field(
377    key: &str,
378    value: &Value,
379    pointer: &str,
380    options: LintOptions,
381    findings: &mut Vec<LintFinding>,
382) {
383    lint_suffix_type(key, value, pointer, options.untyped_text_scalars, findings);
384    if options.minimum_severity == LintSeverity::Warning {
385        lint_missing_suffix(key, value, pointer, options.untyped_text_scalars, findings);
386    }
387    lint_value_at(value, pointer, Some(key), options, findings);
388}
389
390fn lint_formatted_quantity(
391    key: Option<&str>,
392    text: &str,
393    pointer: &str,
394    findings: &mut Vec<LintFinding>,
395) {
396    let Some(advice) = formatted_quantity_advice(text) else {
397        return;
398    };
399    if let Some(key) = key {
400        let last_word = key.rsplit(['_', '-']).next().unwrap_or(key);
401        const TEXT_FIELDS: &[&str] = &[
402            "Version", "Id", "Code", "Zip", "Postcode", "Phone", "Sku", "Label", "Name", "Title",
403            "Sqlstate",
404        ];
405        let is_text = TEXT_FIELDS
406            .iter()
407            .any(|word| last_word.eq_ignore_ascii_case(word) || last_word.ends_with(word))
408            || last_word.ends_with("ID")
409            || last_word.ends_with("SKU");
410        let has_text_suffix = [
411            "_epoch_ns",
412            "_sats",
413            "_msats",
414            "_rfc3339",
415            "_rfc3339_date",
416            "_rfc3339_time",
417            "_bcp47",
418            "_utc_offset",
419            "_url",
420            "_secret",
421        ]
422        .iter()
423        .any(|suffix| crate::formatting::has_suffix_ci(key, suffix));
424        if is_text || has_text_suffix {
425            return;
426        }
427    }
428    findings.push(LintFinding::warning(
429        "formatted_quantity_string",
430        pointer,
431        format!("Value looks like a formatted quantity: {advice}. Format it for display at the presentation boundary"),
432    ));
433}
434
435fn ascii_digits(text: &str) -> bool {
436    !text.is_empty() && text.bytes().all(|byte| byte.is_ascii_digit())
437}
438
439const GROUP_SEPARATORS: [char; 5] = [',', '.', ' ', '\u{a0}', '\u{202f}'];
440
441fn grouped_digits(text: &str) -> bool {
442    GROUP_SEPARATORS.into_iter().any(|separator| {
443        let Some((first, rest)) = text.split_once(separator) else {
444            return false;
445        };
446        first.len() <= 3
447            && ascii_digits(first)
448            && rest
449                .split(separator)
450                .all(|group| group.len() == 3 && ascii_digits(group))
451    })
452}
453
454fn decimal_quantity(text: &str) -> bool {
455    ascii_digits(text)
456        || grouped_digits(text)
457        || text
458            .rsplit_once(['.', ','])
459            .is_some_and(|(whole, fractional)| {
460                (ascii_digits(whole) || grouped_digits(whole)) && ascii_digits(fractional)
461            })
462}
463
464fn formatted_quantity_advice(text: &str) -> Option<&'static str> {
465    if matches!(text, "—" | "-")
466        || text.eq_ignore_ascii_case("n/a")
467        || text.eq_ignore_ascii_case("none")
468    {
469        return Some("send null for an absent value");
470    }
471    let text = text.strip_prefix(['-', '+', '−']).unwrap_or(text);
472    if ascii_digits(text) || grouped_digits(text) {
473        return Some("send a JSON number");
474    }
475    if let Some((hours, rest)) = text.split_once(':')
476        && let Some((minutes, seconds)) = rest.split_once(':')
477        && hours.len() >= 2
478        && ascii_digits(hours)
479        && [minutes, seconds]
480            .iter()
481            .all(|part| part.len() == 2 && ascii_digits(part) && *part < "60")
482    {
483        return Some("send a numeric duration with the _s suffix");
484    }
485    let duration_units = ['d', 'h', 'm', 's'];
486    let mut units = duration_units.iter();
487    if text.contains(' ')
488        && text.split(' ').all(|part| {
489            let number = part.trim_end_matches(duration_units);
490            ascii_digits(number) && units.any(|unit| part.strip_suffix(*unit) == Some(number))
491        })
492    {
493        return Some("send a numeric duration with the _s suffix");
494    }
495    if let Some((symbol, number)) = text.split_at_checked(text.chars().next()?.len_utf8())
496        && decimal_quantity(number.trim_start_matches([' ', '\u{a0}', '\u{202f}']))
497    {
498        match symbol {
499            "$" => return Some("send integer minor units with the currency-specific suffix"),
500            "€" => return Some("send integer cents with the _eur_cents suffix"),
501            "¥" => return Some("send integer yen with the _jpy suffix for JPY"),
502            "£" => return Some("send integer pence with the _gbp_cents suffix"),
503            _ => {}
504        }
505    }
506    let split = text.find(|c: char| !c.is_ascii_digit() && !GROUP_SEPARATORS.contains(&c))?;
507    // The unit follows the number; grouping whitespace can also precede it.
508    let (number, unit) = text.split_at(split);
509    if !decimal_quantity(number.trim_end_matches([' ', '\u{a0}', '\u{202f}'])) {
510        return None;
511    }
512    match unit {
513        "B" | "byte" | "bytes" | "kB" | "KB" | "MB" | "GB" | "TB" | "PB" | "EB" | "KiB" | "MiB"
514        | "GiB" | "TiB" | "PiB" | "EiB" => Some("send integer bytes with the _bytes suffix"),
515        "ns" | "nanosecond" | "nanoseconds" => Some("send a number with the _ns suffix"),
516        "us" | "µs" | "μs" | "microsecond" | "microseconds" => {
517            Some("send a number with the _us suffix")
518        }
519        "ms" | "millisecond" | "milliseconds" => Some("send a number with the _ms suffix"),
520        "s" | "sec" | "second" | "seconds" => Some("send a number with the _s suffix"),
521        "m" | "min" | "minute" | "minutes" => Some("send a number with the _minutes suffix"),
522        "h" | "hr" | "hour" | "hours" => Some("send a number with the _hours suffix"),
523        "d" | "day" | "days" => Some("send a number with the _days suffix"),
524        "%" | "percent" => Some("send a number with the _percent suffix"),
525        "°C" | "°F" | "K" => {
526            Some("send a number and identify the temperature scale in the field name")
527        }
528        "sat" | "sats" => Some("send an integer with the _sats suffix"),
529        "msat" | "msats" => Some("send an integer with the _msats suffix"),
530        "JPY" => Some("send integer yen with the _jpy suffix"),
531        "USD" => Some("send integer cents with the _usd_cents suffix"),
532        "EUR" => Some("send integer cents with the _eur_cents suffix"),
533        _ => None,
534    }
535}
536
537fn lint_schema_property(
538    name: &str,
539    schema: &Value,
540    properties_pointer: &str,
541    options: LintOptions,
542    findings: &mut Vec<LintFinding>,
543) {
544    let property_pointer = join_pointer(properties_pointer, name);
545    let normalized_name = name.to_ascii_lowercase();
546    if !matches!(schema, Value::Object(_) | Value::Bool(_)) {
547        lint_field(
548            name,
549            schema,
550            &property_pointer,
551            options.untyped_text_scalars(false),
552            findings,
553        );
554        return;
555    }
556    if normalized_name.ends_with("_secret")
557        && let Some(object) = schema.as_object()
558    {
559        for field in ["default", "example"] {
560            if let Some(value) = object.get(field)
561                && !is_redacted_secret_literal(value)
562            {
563                findings.push(LintFinding::error(
564                    "secret_schema_value_exposed",
565                    join_pointer(&property_pointer, field),
566                    format!("schema property {name:?} exposes secret {field}"),
567                ));
568            }
569        }
570        if let Some(Value::Array(examples)) = object.get("examples") {
571            for (index, value) in examples.iter().enumerate() {
572                if !is_redacted_secret_literal(value) {
573                    findings.push(LintFinding::error(
574                        "secret_schema_value_exposed",
575                        join_pointer(
576                            &join_pointer(&property_pointer, "examples"),
577                            &index.to_string(),
578                        ),
579                        format!("schema property {name:?} exposes secret example"),
580                    ));
581                }
582            }
583        }
584    }
585    lint_schema_suffix_type(name, schema, &property_pointer, findings);
586    lint_value_at(
587        schema,
588        &property_pointer,
589        Some(name),
590        options.untyped_text_scalars(false),
591        findings,
592    );
593}
594
595fn lint_schema_suffix_type(
596    name: &str,
597    schema: &Value,
598    pointer: &str,
599    findings: &mut Vec<LintFinding>,
600) {
601    let normalized = name.to_ascii_lowercase();
602    let (expected, description): (&[&str], &str) = if normalized.ends_with("_bytes") {
603        (&["integer"], "an integer byte count")
604    } else if normalized.ends_with("_epoch_s") || normalized.ends_with("_epoch_ms") {
605        (&["integer"], "an integer epoch timestamp")
606    } else if normalized.ends_with("_epoch_ns") {
607        (&["string"], "a decimal integer string")
608    } else if normalized.ends_with("_sats") || normalized.ends_with("_msats") {
609        (
610            &["integer", "string"],
611            "an integer or decimal integer string",
612        )
613    } else if normalized.ends_with("_percent") || is_duration_suffix(&normalized) {
614        (&["integer", "number"], "a numeric value")
615    } else if is_currency_minor_unit_suffix(&normalized) {
616        (&["integer"], "an integer currency amount")
617    } else if normalized.ends_with("_rfc3339")
618        || normalized.ends_with("_url")
619        || normalized.ends_with("_bcp47")
620        || normalized.ends_with("_rfc3339_date")
621        || normalized.ends_with("_rfc3339_time")
622        || normalized.ends_with("_utc_offset")
623    {
624        (&["string"], "a string")
625    } else {
626        return;
627    };
628
629    if !schema_accepts_any_type(schema, expected) {
630        findings.push(LintFinding::error(
631            "suffix_type_mismatch",
632            join_pointer(pointer, "type"),
633            format!("schema property {name:?} must allow {description}"),
634        ));
635    }
636}
637
638fn schema_accepts_any_type(schema: &Value, expected: &[&str]) -> bool {
639    let Some(object) = schema.as_object() else {
640        return true;
641    };
642
643    if let Some(schema_type) = object.get("type") {
644        let items_accepts = || match object.get("items") {
645            Some(items @ Value::Object(_)) => schema_accepts_any_type(items, expected),
646            _ => true,
647        };
648        return match schema_type {
649            Value::String(value) if value == "array" => items_accepts(),
650            Value::String(value) => expected.contains(&value.as_str()),
651            Value::Array(values) => values.iter().any(|value| match value.as_str() {
652                Some("array") => items_accepts(),
653                Some(t) => expected.contains(&t),
654                None => false,
655            }),
656            _ => true,
657        };
658    }
659
660    for keyword in ["anyOf", "oneOf"] {
661        if let Some(Value::Array(branches)) = object.get(keyword) {
662            return branches
663                .iter()
664                .any(|branch| schema_accepts_any_type(branch, expected));
665        }
666    }
667    if let Some(Value::Array(branches)) = object.get("allOf") {
668        return branches
669            .iter()
670            .all(|branch| schema_accepts_any_type(branch, expected));
671    }
672    true
673}
674
675fn is_redacted_secret_literal(value: &Value) -> bool {
676    matches!(value, Value::Null) || matches!(value, Value::String(text) if text == "***")
677}
678
679const REGISTERED_SUFFIXES: &[(&str, &[&str])] = &[
680    (
681        "duration",
682        &["_ns", "_us", "_ms", "_s", "_minutes", "_hours", "_days"],
683    ),
684    (
685        "timestamp",
686        &["_epoch_s", "_epoch_ms", "_epoch_ns", "_rfc3339"],
687    ),
688    (
689        "strict_string",
690        &["_rfc3339_date", "_rfc3339_time", "_bcp47", "_utc_offset"],
691    ),
692    ("size", &["_bytes"]),
693    ("percentage", &["_percent"]),
694    (
695        "currency",
696        &[
697            "_msats",
698            "_sats",
699            "_usd_cents",
700            "_eur_cents",
701            "_jpy",
702            "_{code}_cents",
703            "_{code}_micro",
704        ],
705    ),
706    ("sensitive", &["_secret", "_url"]),
707];
708
709const UNSUFFIXED_STEMS: &[(&str, &str)] = &[
710    ("timeout", "duration"),
711    ("elapsed", "duration"),
712    ("duration", "duration"),
713    ("ttl", "duration"),
714    ("interval", "duration"),
715    ("latency", "duration"),
716    ("delay", "duration"),
717    ("uptime", "duration"),
718    ("price", "currency"),
719    ("amount", "currency"),
720    ("cost", "currency"),
721    ("fee", "currency"),
722    ("balance", "currency"),
723    ("subtotal", "currency"),
724    ("revenue", "currency"),
725    ("created", "timestamp"),
726    ("updated", "timestamp"),
727    ("modified", "timestamp"),
728    ("expires", "timestamp"),
729    ("issued", "timestamp"),
730    ("timestamp", "timestamp"),
731    ("apikey", "sensitive"),
732    ("api_key", "sensitive"),
733    ("token", "sensitive"),
734    ("password", "sensitive"),
735    ("passwd", "sensitive"),
736    ("secret", "sensitive"),
737    ("credential", "sensitive"),
738];
739
740/// Whether a key already carries a suffix the renderer and redactor act on.
741///
742/// Matching is the convention's own rule — the suffix spelled all-lowercase or
743/// all-uppercase, never mixed — because this decides whether the linter stays
744/// quiet. Accepting `api_Secret` here would report a field as marked while
745/// `redaction.rs` leaves it in the clear, which is the one mistake a linter
746/// used as a leak guard must not make.
747fn has_registered_suffix(key: &str) -> bool {
748    REGISTERED_SUFFIXES
749        .iter()
750        .flat_map(|(_, suffixes)| suffixes.iter())
751        .any(|suffix| match suffix.strip_prefix("_{code}") {
752            Some(tail) => crate::formatting::strip_suffix_ci(key, tail)
753                .as_deref()
754                .and_then(|rest| rest.rsplit_once('_').map(|(_, code)| code.to_string()))
755                .is_some_and(|code| {
756                    (3..=4).contains(&code.len())
757                        && code
758                            .chars()
759                            .all(|character| character.is_ascii_alphabetic())
760                }),
761            None => crate::formatting::has_suffix_ci(key, suffix),
762        })
763}
764
765fn parse_json_number_text(text: &str) -> Option<Value> {
766    serde_json::from_str::<serde_json::Number>(text)
767        .ok()
768        .map(Value::Number)
769}
770
771fn is_numeric_suffix(key: &str) -> bool {
772    let has = |suffix: &str| crate::formatting::has_suffix_ci(key, suffix);
773    has("_bytes")
774        || has("_epoch_s")
775        || has("_epoch_ms")
776        || has("_sats")
777        || has("_msats")
778        || has("_percent")
779        || is_duration_suffix(key)
780        || is_currency_minor_unit_suffix(key)
781}
782
783fn lint_missing_suffix(
784    key: &str,
785    value: &Value,
786    pointer: &str,
787    untyped_text_scalars: bool,
788    findings: &mut Vec<LintFinding>,
789) {
790    if value.is_null() || has_registered_suffix(key) {
791        return;
792    }
793    let lower = key.to_ascii_lowercase();
794    let category = if lower.ends_with("_at") {
795        Some("timestamp")
796    } else {
797        UNSUFFIXED_STEMS
798            .iter()
799            .find(|(stem, _)| {
800                lower == *stem
801                    || lower.ends_with(&format!("_{stem}"))
802                    || lower == format!("{stem}s")
803                    || lower.ends_with(&format!("_{stem}s"))
804            })
805            .map(|(_, category)| *category)
806    };
807    let Some(category) = category else {
808        return;
809    };
810    let is_plausible_scalar = |val: &Value| {
811        let is_numeric = val.is_number()
812            || (untyped_text_scalars && val.as_str().and_then(parse_json_number_text).is_some());
813        match category {
814            "duration" | "currency" | "size" | "percentage" => is_numeric,
815            "timestamp" => is_numeric || val.is_string(),
816            _ => val.is_string(),
817        }
818    };
819    let plausible = if let Some(items) = value.as_array() {
820        let mut has_non_null = false;
821        let mut all_valid = true;
822        for item in items {
823            if item.is_null() {
824                continue;
825            }
826            has_non_null = true;
827            if !is_plausible_scalar(item) {
828                all_valid = false;
829                break;
830            }
831        }
832        has_non_null && all_valid
833    } else {
834        is_plausible_scalar(value)
835    };
836    if !plausible {
837        return;
838    }
839    let suffixes = REGISTERED_SUFFIXES
840        .iter()
841        .find(|(name, _)| *name == category)
842        .map(|(_, suffixes)| suffixes.join(", "))
843        .unwrap_or_default();
844    let message = if category == "sensitive" {
845        format!(
846            "`{key}` looks like a credential but is not marked, so it is printed and logged in \
847             the clear. Rename it with one of: {suffixes}"
848        )
849    } else {
850        format!(
851            "`{key}` names a {category} but carries no unit, so a reader cannot tell what it \
852             means without asking. Rename it with one of: {suffixes}"
853        )
854    };
855    findings.push(LintFinding::warning(
856        "missing_suffix",
857        pointer.to_string(),
858        message,
859    ));
860}
861
862fn lint_suffix_scalar_message(key: &str, value: &Value) -> Option<String> {
863    // Suffix recognition uses the convention's own matching rule, not a
864    // case-folded approximation: a key the renderer treats as plain must not be
865    // held to a suffix's type contract, or the fix the message asks for leaves
866    // the field just as untreated as before.
867    let has = |suffix: &str| crate::formatting::has_suffix_ci(key, suffix);
868    if has("_bytes") {
869        (!is_non_negative_integer(value))
870            .then(|| format!("{key:?} must be a non-negative integer byte count"))
871    } else if has("_epoch_s") || has("_epoch_ms") {
872        (!is_integer(value)).then(|| format!("{key:?} must be an integer epoch timestamp"))
873    } else if has("_epoch_ns") {
874        (!is_decimal_integer_string(value))
875            .then(|| format!("{key:?} must be a decimal integer string"))
876    } else if has("_sats") || has("_msats") {
877        (!(is_integer(value) || is_decimal_integer_string(value)))
878            .then(|| format!("{key:?} must be an integer or decimal integer string"))
879    } else if has("_percent") {
880        (!value.is_number()).then(|| format!("{key:?} must be numeric"))
881    } else if is_duration_suffix(key) {
882        (!value.is_number()).then(|| format!("{key:?} must be a numeric duration"))
883    } else if is_currency_minor_unit_suffix(key) {
884        (!is_integer(value)).then(|| format!("{key:?} must be an integer currency amount"))
885    } else if has("_rfc3339") {
886        if value.as_str().is_some_and(is_valid_rfc3339) {
887            None
888        } else if value.is_string() {
889            Some(format!(
890                "{key:?} must be an RFC 3339 date-time with a mandatory offset (e.g. \
891                 2026-02-14T10:30:00Z)"
892            ))
893        } else {
894            Some(format!("{key:?} must be a string"))
895        }
896    } else if has("_bcp47") {
897        if value.as_str().is_some_and(is_valid_bcp47) {
898            None
899        } else if value.is_string() {
900            Some(format!("{key:?} must be a well-formed BCP 47 language tag"))
901        } else {
902            Some(format!("{key:?} must be a string"))
903        }
904    } else if has("_rfc3339_date") {
905        if value.as_str().is_some_and(is_valid_rfc3339_date) {
906            None
907        } else if value.is_string() {
908            Some(format!(
909                "{key:?} must be an RFC 3339 full-date (YYYY-MM-DD)"
910            ))
911        } else {
912            Some(format!("{key:?} must be a string"))
913        }
914    } else if has("_rfc3339_time") {
915        if value.as_str().is_some_and(is_valid_rfc3339_time) {
916            None
917        } else if value.is_string() {
918            Some(format!(
919                "{key:?} must be an RFC 3339 partial-time (HH:MM:SS[.fraction], no Z or offset)"
920            ))
921        } else {
922            Some(format!("{key:?} must be a string"))
923        }
924    } else if has("_utc_offset") {
925        if value.as_str().and_then(normalize_utc_offset).is_some() {
926            None
927        } else if value.is_string() {
928            Some(format!(
929                "{key:?} must be a fixed UTC offset (\"UTC\" or ±HH:MM)"
930            ))
931        } else {
932            Some(format!("{key:?} must be a string"))
933        }
934    } else {
935        None
936    }
937}
938
939fn lint_suffix_type(
940    key: &str,
941    value: &Value,
942    pointer: &str,
943    untyped_text_scalars: bool,
944    findings: &mut Vec<LintFinding>,
945) {
946    if value.is_null() {
947        return;
948    }
949    if untyped_text_scalars
950        && let Some(text) = value.as_str()
951        && is_numeric_suffix(key)
952    {
953        if text.is_empty() {
954            return;
955        }
956        let message = match parse_json_number_text(text) {
957            Some(num_val) => lint_suffix_scalar_message(key, &num_val),
958            None => Some(format!("{key:?} must be a decimal numeric text value")),
959        };
960        if let Some(message) = message {
961            findings.push(LintFinding::error(
962                "suffix_type_mismatch",
963                pointer.to_string(),
964                message,
965            ));
966        }
967        return;
968    }
969    let has = |suffix: &str| crate::formatting::has_suffix_ci(key, suffix);
970    if has("_url") {
971        // Redaction walks a URL-marked collection into its string leaves, so a
972        // collection is a shape the convention supports, not a type error. Only
973        // the leaves are held to the single-URL rule.
974        let message = match url_field_violation(value) {
975            UrlFieldCheck::Ok => None,
976            UrlFieldCheck::NotAUrl => Some(format!(
977                "{key:?} must be a single URL (no internal whitespace or bare credentials)"
978            )),
979            UrlFieldCheck::NotAString => Some(format!(
980                "{key:?} must be a URL string, or a collection whose leaves are URL strings"
981            )),
982        };
983        if let Some(message) = message {
984            findings.push(LintFinding::error(
985                "suffix_type_mismatch",
986                pointer.to_string(),
987                message,
988            ));
989        }
990        return;
991    }
992    if has("_secret") {
993        return;
994    }
995    if let Some(items) = value.as_array() {
996        for (idx, item) in items.iter().enumerate() {
997            if item.is_null() {
998                continue;
999            }
1000            let item_pointer = format!("{pointer}/{idx}");
1001            let message = if item.is_array() {
1002                Some(format!("{key:?} array elements must be scalar values"))
1003            } else {
1004                lint_suffix_scalar_message(key, item)
1005            };
1006            if let Some(message) = message {
1007                findings.push(LintFinding::error(
1008                    "suffix_type_mismatch",
1009                    item_pointer,
1010                    message,
1011                ));
1012            }
1013        }
1014        return;
1015    }
1016    if let Some(message) = lint_suffix_scalar_message(key, value) {
1017        findings.push(LintFinding::error(
1018            "suffix_type_mismatch",
1019            pointer.to_string(),
1020            message,
1021        ));
1022    }
1023}
1024
1025fn lint_unsafe_integer(value: &Value, pointer: &str, findings: &mut Vec<LintFinding>) {
1026    let Value::Number(number) = value else {
1027        return;
1028    };
1029    if !number_is_integer_literal(number) {
1030        return;
1031    }
1032    let exceeds_safe_range = if let Some(value) = number.as_i128() {
1033        value.unsigned_abs() > u128::from(MAX_SAFE_INTEGER)
1034    } else if let Some(value) = number.as_u128() {
1035        value > u128::from(MAX_SAFE_INTEGER)
1036    } else if let Some(value) = number.as_f64() {
1037        value.abs() > MAX_SAFE_INTEGER as f64
1038    } else {
1039        // An exact integer too large even for a finite f64 is necessarily
1040        // outside JavaScript's safe-integer range.
1041        true
1042    };
1043    if exceeds_safe_range {
1044        findings.push(unsafe_integer_finding(pointer));
1045    }
1046}
1047
1048fn unsafe_integer_finding(pointer: &str) -> LintFinding {
1049    LintFinding::error(
1050        "unsafe_integer",
1051        pointer.to_string(),
1052        "integer exceeds JavaScript safe integer range ±(2^53-1)".to_string(),
1053    )
1054}
1055
1056fn is_integer(value: &Value) -> bool {
1057    matches!(value, Value::Number(number) if number_is_integer(number))
1058}
1059
1060fn is_non_negative_integer(value: &Value) -> bool {
1061    let Value::Number(number) = value else {
1062        return false;
1063    };
1064    if !number_is_integer(number) {
1065        return false;
1066    }
1067    let text = number.to_string();
1068    !text.starts_with('-') || decimal_number_is_zero(&text)
1069}
1070
1071/// Whether a JSON number's exact mathematical value is an integer.
1072///
1073/// `serde_json/arbitrary_precision` preserves the source decimal, so this
1074/// handles integral-valued decimals and exponents without rounding through
1075/// f64, while also accepting integers larger than u128.
1076fn number_is_integer(number: &Number) -> bool {
1077    decimal_number_is_integer(&number.to_string())
1078}
1079
1080/// Whether the producer wrote this number as an integer literal.
1081///
1082/// The unsafe-integer rule is about an integer that cannot survive a JavaScript
1083/// round trip, so it keys off the written form rather than the mathematical
1084/// value. `1.5e300` and `1.0e17` are float literals: already doubles by
1085/// construction, carrying no exactness promise to break. `100000000000000000`
1086/// does carry one, and breaks it.
1087fn number_is_integer_literal(number: &Number) -> bool {
1088    crate::formatting::number_is_integer_literal(number)
1089}
1090
1091fn decimal_number_is_integer(text: &str) -> bool {
1092    let unsigned = text.trim_prefix('-');
1093    let exponent_index = unsigned.find(['e', 'E']);
1094    let (mantissa, exponent_text) = exponent_index.map_or((unsigned, None), |index| {
1095        (&unsigned[..index], Some(&unsigned[index + 1..]))
1096    });
1097    if mantissa
1098        .bytes()
1099        .filter(|byte| *byte != b'.')
1100        .all(|byte| byte == b'0')
1101    {
1102        return true;
1103    }
1104
1105    let fraction_digits = mantissa
1106        .split_once('.')
1107        .map_or(0, |(_, fraction)| fraction.len());
1108    let exponent = exponent_text.map_or(0, |value| {
1109        value.parse::<i128>().unwrap_or_else(|_| {
1110            if value.starts_with('-') {
1111                i128::MIN
1112            } else {
1113                i128::MAX
1114            }
1115        })
1116    });
1117    let scale = exponent.saturating_sub(i128::try_from(fraction_digits).unwrap_or(i128::MAX));
1118    if scale >= 0 {
1119        return true;
1120    }
1121
1122    let required_trailing_zeroes = scale.unsigned_abs();
1123    let digit_count = mantissa.bytes().filter(|byte| *byte != b'.').count();
1124    if required_trailing_zeroes > digit_count as u128 {
1125        return false;
1126    }
1127    mantissa
1128        .bytes()
1129        .filter(|byte| *byte != b'.')
1130        .rev()
1131        .take(required_trailing_zeroes as usize)
1132        .all(|byte| byte == b'0')
1133}
1134
1135fn decimal_number_is_zero(text: &str) -> bool {
1136    let unsigned = text.trim_prefix('-');
1137    let mantissa = unsigned
1138        .split_once(['e', 'E'])
1139        .map_or(unsigned, |(mantissa, _)| mantissa);
1140    mantissa
1141        .bytes()
1142        .filter(|byte| *byte != b'.')
1143        .all(|byte| byte == b'0')
1144}
1145
1146fn is_decimal_integer_string(value: &Value) -> bool {
1147    let Value::String(text) = value else {
1148        return false;
1149    };
1150    let digits = text.trim_prefix('-');
1151    !digits.is_empty() && digits.chars().all(|character| character.is_ascii_digit())
1152}
1153
1154fn is_duration_suffix(key: &str) -> bool {
1155    ["_ns", "_us", "_ms", "_s", "_minutes", "_hours", "_days"]
1156        .iter()
1157        .any(|suffix| crate::formatting::has_suffix_ci(key, suffix))
1158}
1159
1160/// Whether a key names a currency minor unit the formatter actually formats.
1161///
1162/// `_cents` and `_micro` carry a currency code (`_usd_cents`); a bare
1163/// `total_cents` is not a registered suffix, and holding it to the integer rule
1164/// would demand a fix that changes nothing about how the field is rendered.
1165fn is_currency_minor_unit_suffix(key: &str) -> bool {
1166    crate::formatting::extract_currency_code(key).is_some()
1167        || crate::formatting::extract_currency_code_micro(key).is_some()
1168        || crate::formatting::has_suffix_ci(key, "_jpy")
1169}
1170
1171/// How a `_url`-marked value compares to the shapes redaction handles.
1172enum UrlFieldCheck {
1173    Ok,
1174    NotAUrl,
1175    NotAString,
1176}
1177
1178/// Redaction gives URL treatment to string leaves and walks collections to
1179/// reach them, so the linter accepts the same shapes and checks the leaves.
1180fn url_field_violation(value: &Value) -> UrlFieldCheck {
1181    match value {
1182        Value::Null => UrlFieldCheck::Ok,
1183        Value::String(text) => {
1184            if is_wellformed_url_field(text) {
1185                UrlFieldCheck::Ok
1186            } else {
1187                UrlFieldCheck::NotAUrl
1188            }
1189        }
1190        Value::Array(items) => first_url_violation(items.iter()),
1191        Value::Object(entries) => first_url_violation(entries.values()),
1192        _ => UrlFieldCheck::NotAString,
1193    }
1194}
1195
1196fn first_url_violation<'value>(values: impl Iterator<Item = &'value Value>) -> UrlFieldCheck {
1197    for value in values {
1198        match url_field_violation(value) {
1199            UrlFieldCheck::Ok => {}
1200            violation => return violation,
1201        }
1202    }
1203    UrlFieldCheck::Ok
1204}
1205
1206fn is_wellformed_url_field(value: &str) -> bool {
1207    if is_scheme_prefixed_url(value) || is_scheme_prefixed_url(value.trim()) {
1208        return true;
1209    }
1210    !value.chars().any(char::is_whitespace) && !value.contains('@')
1211}
1212
1213fn is_scheme_prefixed_url(value: &str) -> bool {
1214    if value.bytes().any(|byte| byte.is_ascii_whitespace()) {
1215        return false;
1216    }
1217    let bytes = value.as_bytes();
1218    if !bytes.first().is_some_and(u8::is_ascii_alphabetic) {
1219        return false;
1220    }
1221    let mut index = 1;
1222    while index < bytes.len() {
1223        let character = bytes[index];
1224        if character.is_ascii_alphanumeric() || matches!(character, b'+' | b'-' | b'.') {
1225            index += 1;
1226        } else {
1227            break;
1228        }
1229    }
1230    value[index..].starts_with("://")
1231}
1232
1233fn join_pointer(base: &str, token: &str) -> String {
1234    let escaped = token.replace('~', "~0").replace('/', "~1");
1235    if base.is_empty() {
1236        format!("/{escaped}")
1237    } else {
1238        format!("{base}/{escaped}")
1239    }
1240}
1241
1242#[cfg(test)]
1243mod tests {
1244    use super::{
1245        LintOptions, LintSeverity, REGISTERED_SUFFIXES, RedactionCanaryError,
1246        assert_no_lint_findings, assert_redaction_canary_absent, assert_strict_event, lint_value,
1247    };
1248    use serde_json::{Value, json};
1249
1250    #[test]
1251    fn lint_fields_separately_from_their_values() {
1252        let options = LintOptions::default().runtime_values();
1253        let findings = super::lint_field_value("total_bytes", &json!([12, "8 MB"]), options);
1254        assert!(findings.iter().any(|finding| {
1255            finding.rule_id == "suffix_type_mismatch" && finding.pointer == "/1"
1256        }));
1257        let findings = assert_no_lint_findings(&json!({"rows": "1,200"})).unwrap_err();
1258        assert_eq!(findings[0].rule_id, "formatted_quantity_string");
1259        assert_eq!(findings[0].pointer, "/rows");
1260    }
1261
1262    #[test]
1263    fn public_lint_api_reports_and_filters_findings() {
1264        let value = json!({
1265            "timeout": 5,
1266            "size_bytes": "large",
1267            "created_rfc3339": "not-a-time"
1268        });
1269        let findings = lint_value(&value, LintOptions::default());
1270        assert_eq!(findings.len(), 3);
1271        assert!(
1272            findings
1273                .iter()
1274                .any(|finding| finding.severity == LintSeverity::Warning)
1275        );
1276        let errors = lint_value(&value, LintOptions::errors_only());
1277        assert_eq!(errors.len(), 2);
1278    }
1279
1280    #[test]
1281    fn integer_suffixes_accept_integral_decimals_and_signed_currency() {
1282        let value: Value = serde_json::from_str(
1283            r#"{
1284                "price_usd_cents": -1,
1285                "refund_eur_cents": -3.0,
1286                "size_bytes": 3.0,
1287                "created_epoch_ms": 3e0
1288            }"#,
1289        )
1290        .unwrap_or_else(|error| panic!("{error}"));
1291
1292        assert!(lint_value(&value, LintOptions::errors_only()).is_empty());
1293    }
1294
1295    #[test]
1296    fn registered_currency_suffixes_accept_three_or_four_letter_codes() {
1297        assert!(super::has_registered_suffix("fare_thb_cents"));
1298        assert!(super::has_registered_suffix("deposit_usdt_cents"));
1299        assert!(!super::has_registered_suffix("total_amount_cents"));
1300        assert!(!super::has_registered_suffix("price_usdtx_cents"));
1301    }
1302
1303    #[test]
1304    fn integer_suffixes_reject_fractional_values_and_negative_bytes() {
1305        let value: Value = serde_json::from_str(
1306            r#"{
1307                "price_usd_cents": 3.5,
1308                "size_bytes": -1
1309            }"#,
1310        )
1311        .unwrap_or_else(|error| panic!("{error}"));
1312        let findings = lint_value(&value, LintOptions::errors_only());
1313
1314        assert_eq!(
1315            findings
1316                .iter()
1317                .filter(|finding| finding.rule_id == "suffix_type_mismatch")
1318                .count(),
1319            2
1320        );
1321    }
1322
1323    #[test]
1324    fn unsafe_integer_finds_values_beyond_u128() {
1325        let value: Value =
1326            serde_json::from_str(r#"{"huge_count":340282366920938463463374607431768211456}"#)
1327                .unwrap_or_else(|error| panic!("{error}"));
1328        let findings = lint_value(&value, LintOptions::errors_only());
1329
1330        assert!(
1331            findings
1332                .iter()
1333                .any(|finding| finding.rule_id == "unsafe_integer"),
1334            "{findings:?}"
1335        );
1336    }
1337
1338    #[test]
1339    fn assertion_helpers_cover_protocol_lint_and_redaction() {
1340        let event = json!({
1341            "kind": "result",
1342            "result": {"code": "ready"},
1343            "trace": {}
1344        });
1345        assert!(assert_strict_event(&event).is_ok());
1346        assert!(assert_no_lint_findings(&event).is_ok());
1347        assert!(assert_redaction_canary_absent("{\"secret\":\"***\"}", "canary-42").is_ok());
1348        assert_eq!(
1349            assert_redaction_canary_absent("contains canary-42", "canary-42"),
1350            Err(RedactionCanaryError::Exposed)
1351        );
1352    }
1353
1354    /// The missing-suffix rule reads intent from the name, so what it stays
1355    /// quiet about matters as much as what it reports. Driven through the
1356    /// public entry point rather than the private helper, so a later move of
1357    /// the rule cannot take the pin with it.
1358    #[test]
1359    fn missing_suffix_reads_intent_from_the_name() {
1360        for (label, value) in [
1361            ("bare dimension name", json!({"timeout": 5000})),
1362            ("suffixed dimension name", json!({"request_timeout": 1})),
1363            ("_at timestamp", json!({"expires_at": 1})),
1364        ] {
1365            let findings = lint_value(&json!(value), LintOptions::default());
1366            assert!(
1367                findings.iter().any(|f| f.rule_id == "missing_suffix"),
1368                "{label}: expected a missing_suffix warning, got {findings:?}"
1369            );
1370        }
1371
1372        for (label, value) in [
1373            ("already labelled duration", json!({"timeout_ms": 5000})),
1374            ("already labelled currency", json!({"price_gbp_cents": 1})),
1375            ("already labelled secret", json!({"api_key_secret": "sk"})),
1376            // A dimension name over a container is a config block, not a bare
1377            // number. This is the guard that has no other test.
1378            (
1379                "dimension name over a container",
1380                json!({"timeout": {"connect": 1}}),
1381            ),
1382            ("credentials block", json!({"credentials": {"user": "x"}})),
1383            ("unrelated name", json!({"name": "demo"})),
1384        ] {
1385            let findings = lint_value(&json!(value), LintOptions::default());
1386            assert!(
1387                findings.is_empty(),
1388                "{label}: expected no findings, got {findings:?}"
1389            );
1390        }
1391    }
1392
1393    /// A canary is only useful if escaping cannot hide it. Every case here is a
1394    /// canary sitting verbatim in the output while a raw substring search
1395    /// misses it, which is how a leak used to pass this assertion.
1396    #[test]
1397    fn redaction_canary_survives_every_output_escape() {
1398        for (label, canary) in [
1399            (
1400                "pem newlines",
1401                "-----BEGIN KEY-----\nabc\n-----END KEY-----",
1402            ),
1403            ("double quote", "p@ss\"word"),
1404            ("backslash path", "C:\\Users\\me\\key"),
1405            ("tab", "a\tb"),
1406            ("non-bmp", "k\u{1f511}ey"),
1407        ] {
1408            let rendered = crate::render(
1409                &json!({ "note": canary }),
1410                crate::OutputFormat::Json,
1411                &crate::OutputOptions::default(),
1412            );
1413            assert!(
1414                rendered.contains("note"),
1415                "{label}: expected the field to survive rendering"
1416            );
1417            assert_eq!(
1418                assert_redaction_canary_absent(&rendered, canary),
1419                Err(RedactionCanaryError::Exposed),
1420                "{label}: escaped canary must still be reported, output was {rendered}"
1421            );
1422        }
1423    }
1424
1425    /// The percent-encoded spelling counts too: a canary can reach the stream
1426    /// through a URL without ever appearing literally.
1427    #[test]
1428    fn redaction_canary_is_found_percent_encoded() {
1429        assert_eq!(
1430            assert_redaction_canary_absent("{\"note\":\"https://h/p?q=a%20b%20c\"}", "a b c"),
1431            Err(RedactionCanaryError::Exposed)
1432        );
1433    }
1434
1435    #[test]
1436    fn redaction_canary_is_found_through_nested_and_mixed_encoding() {
1437        for serialized in [
1438            r#"{"note":"https://h/?next=https%3A%2F%2Fb%2F%3Fq%3D%2573ecret"}"#,
1439            r#"{"note":"\u002573ecret"}"#,
1440            r#"{"note":"%5Cu0073ecret"}"#,
1441            r#"{"note":"%255CuD83D%255CuDD11"}"#,
1442        ] {
1443            let canary = if serialized.contains("D83D") {
1444                "🔑"
1445            } else {
1446                "secret"
1447            };
1448            assert_eq!(
1449                assert_redaction_canary_absent(serialized, canary),
1450                Err(RedactionCanaryError::Exposed),
1451                "encoded output must still report the canary: {serialized}"
1452            );
1453        }
1454        assert_eq!(
1455            assert_redaction_canary_absent("%25not-a-canary", "secret"),
1456            Ok(())
1457        );
1458    }
1459
1460    #[test]
1461    fn redaction_canary_inspection_fails_closed_on_excessive_encoding_depth() {
1462        let ordinary = format!("%{}73afe", "25".repeat(15));
1463        assert_eq!(assert_redaction_canary_absent(&ordinary, "secret"), Ok(()));
1464        // No canary is present, but inspection may not silently pass an output
1465        // whose encoding cannot settle inside its fixed work budget.
1466        let deep = format!("%{}73afe{}", "25".repeat(1000), "x".repeat(4096));
1467        assert_eq!(
1468            assert_redaction_canary_absent(&deep, "secret"),
1469            Err(RedactionCanaryError::InspectionLimitExceeded)
1470        );
1471    }
1472
1473    /// The widened search must not cry wolf: a genuinely redacted secret
1474    /// reports clean in every format, whatever characters it contained.
1475    #[test]
1476    fn redaction_canary_stays_quiet_when_the_value_was_redacted() {
1477        for canary in [
1478            "-----BEGIN KEY-----\nabc\n-----END KEY-----",
1479            "p@ss\"word",
1480            "C:\\Users\\me\\key",
1481            "k\u{1f511}ey",
1482        ] {
1483            for format in [
1484                crate::OutputFormat::Json,
1485                crate::OutputFormat::Yaml,
1486                crate::OutputFormat::Plain,
1487            ] {
1488                let rendered = crate::render(
1489                    &json!({ "note_secret": canary }),
1490                    format,
1491                    &crate::OutputOptions::default(),
1492                );
1493                assert_eq!(
1494                    assert_redaction_canary_absent(&rendered, canary),
1495                    Ok(()),
1496                    "redacted output must not report a leak, output was {rendered}"
1497                );
1498            }
1499        }
1500    }
1501
1502    #[test]
1503    fn registry_suffixes_match_the_lint_table() {
1504        const REGISTRY: &str =
1505            include_str!("../../skills/agent-first-data/references/registry.json");
1506        let registry: Value =
1507            serde_json::from_str(REGISTRY).unwrap_or_else(|error| panic!("{error}"));
1508        let suffixes = registry["suffixes"]
1509            .as_array()
1510            .map(Vec::as_slice)
1511            .unwrap_or(&[]);
1512        let mut from_registry: Vec<(String, String)> = suffixes
1513            .iter()
1514            .filter_map(|entry| {
1515                Some((
1516                    entry["category"].as_str()?.to_string(),
1517                    entry["suffix"].as_str()?.to_string(),
1518                ))
1519            })
1520            .collect();
1521        let mut from_table: Vec<(String, String)> = REGISTERED_SUFFIXES
1522            .iter()
1523            .flat_map(|(category, suffixes)| {
1524                suffixes
1525                    .iter()
1526                    .map(move |suffix| ((*category).to_string(), (*suffix).to_string()))
1527            })
1528            .collect();
1529        from_registry.sort();
1530        from_table.sort();
1531        assert_eq!(from_table, from_registry);
1532    }
1533}