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            // Only a suffix makes an element's type part of the contract: a
1002            // plain collection name (`rows`, `edits`) may hold any shape.
1003            let message = if item.is_array() {
1004                has_registered_suffix(key)
1005                    .then(|| format!("{key:?} array elements must be scalar values"))
1006            } else {
1007                lint_suffix_scalar_message(key, item)
1008            };
1009            if let Some(message) = message {
1010                findings.push(LintFinding::error(
1011                    "suffix_type_mismatch",
1012                    item_pointer,
1013                    message,
1014                ));
1015            }
1016        }
1017        return;
1018    }
1019    if let Some(message) = lint_suffix_scalar_message(key, value) {
1020        findings.push(LintFinding::error(
1021            "suffix_type_mismatch",
1022            pointer.to_string(),
1023            message,
1024        ));
1025    }
1026}
1027
1028fn lint_unsafe_integer(value: &Value, pointer: &str, findings: &mut Vec<LintFinding>) {
1029    let Value::Number(number) = value else {
1030        return;
1031    };
1032    if !number_is_integer_literal(number) {
1033        return;
1034    }
1035    let exceeds_safe_range = if let Some(value) = number.as_i128() {
1036        value.unsigned_abs() > u128::from(MAX_SAFE_INTEGER)
1037    } else if let Some(value) = number.as_u128() {
1038        value > u128::from(MAX_SAFE_INTEGER)
1039    } else if let Some(value) = number.as_f64() {
1040        value.abs() > MAX_SAFE_INTEGER as f64
1041    } else {
1042        // An exact integer too large even for a finite f64 is necessarily
1043        // outside JavaScript's safe-integer range.
1044        true
1045    };
1046    if exceeds_safe_range {
1047        findings.push(unsafe_integer_finding(pointer));
1048    }
1049}
1050
1051fn unsafe_integer_finding(pointer: &str) -> LintFinding {
1052    LintFinding::error(
1053        "unsafe_integer",
1054        pointer.to_string(),
1055        "integer exceeds JavaScript safe integer range ±(2^53-1)".to_string(),
1056    )
1057}
1058
1059fn is_integer(value: &Value) -> bool {
1060    matches!(value, Value::Number(number) if number_is_integer(number))
1061}
1062
1063fn is_non_negative_integer(value: &Value) -> bool {
1064    let Value::Number(number) = value else {
1065        return false;
1066    };
1067    if !number_is_integer(number) {
1068        return false;
1069    }
1070    let text = number.to_string();
1071    !text.starts_with('-') || decimal_number_is_zero(&text)
1072}
1073
1074/// Whether a JSON number's exact mathematical value is an integer.
1075///
1076/// `serde_json/arbitrary_precision` preserves the source decimal, so this
1077/// handles integral-valued decimals and exponents without rounding through
1078/// f64, while also accepting integers larger than u128.
1079fn number_is_integer(number: &Number) -> bool {
1080    decimal_number_is_integer(&number.to_string())
1081}
1082
1083/// Whether the producer wrote this number as an integer literal.
1084///
1085/// The unsafe-integer rule is about an integer that cannot survive a JavaScript
1086/// round trip, so it keys off the written form rather than the mathematical
1087/// value. `1.5e300` and `1.0e17` are float literals: already doubles by
1088/// construction, carrying no exactness promise to break. `100000000000000000`
1089/// does carry one, and breaks it.
1090fn number_is_integer_literal(number: &Number) -> bool {
1091    crate::formatting::number_is_integer_literal(number)
1092}
1093
1094fn decimal_number_is_integer(text: &str) -> bool {
1095    let unsigned = text.trim_prefix('-');
1096    let exponent_index = unsigned.find(['e', 'E']);
1097    let (mantissa, exponent_text) = exponent_index.map_or((unsigned, None), |index| {
1098        (&unsigned[..index], Some(&unsigned[index + 1..]))
1099    });
1100    if mantissa
1101        .bytes()
1102        .filter(|byte| *byte != b'.')
1103        .all(|byte| byte == b'0')
1104    {
1105        return true;
1106    }
1107
1108    let fraction_digits = mantissa
1109        .split_once('.')
1110        .map_or(0, |(_, fraction)| fraction.len());
1111    let exponent = exponent_text.map_or(0, |value| {
1112        value.parse::<i128>().unwrap_or_else(|_| {
1113            if value.starts_with('-') {
1114                i128::MIN
1115            } else {
1116                i128::MAX
1117            }
1118        })
1119    });
1120    let scale = exponent.saturating_sub(i128::try_from(fraction_digits).unwrap_or(i128::MAX));
1121    if scale >= 0 {
1122        return true;
1123    }
1124
1125    let required_trailing_zeroes = scale.unsigned_abs();
1126    let digit_count = mantissa.bytes().filter(|byte| *byte != b'.').count();
1127    if required_trailing_zeroes > digit_count as u128 {
1128        return false;
1129    }
1130    mantissa
1131        .bytes()
1132        .filter(|byte| *byte != b'.')
1133        .rev()
1134        .take(required_trailing_zeroes as usize)
1135        .all(|byte| byte == b'0')
1136}
1137
1138fn decimal_number_is_zero(text: &str) -> bool {
1139    let unsigned = text.trim_prefix('-');
1140    let mantissa = unsigned
1141        .split_once(['e', 'E'])
1142        .map_or(unsigned, |(mantissa, _)| mantissa);
1143    mantissa
1144        .bytes()
1145        .filter(|byte| *byte != b'.')
1146        .all(|byte| byte == b'0')
1147}
1148
1149fn is_decimal_integer_string(value: &Value) -> bool {
1150    let Value::String(text) = value else {
1151        return false;
1152    };
1153    let digits = text.trim_prefix('-');
1154    !digits.is_empty() && digits.chars().all(|character| character.is_ascii_digit())
1155}
1156
1157fn is_duration_suffix(key: &str) -> bool {
1158    ["_ns", "_us", "_ms", "_s", "_minutes", "_hours", "_days"]
1159        .iter()
1160        .any(|suffix| crate::formatting::has_suffix_ci(key, suffix))
1161}
1162
1163/// Whether a key names a currency minor unit the formatter actually formats.
1164///
1165/// `_cents` and `_micro` carry a currency code (`_usd_cents`); a bare
1166/// `total_cents` is not a registered suffix, and holding it to the integer rule
1167/// would demand a fix that changes nothing about how the field is rendered.
1168fn is_currency_minor_unit_suffix(key: &str) -> bool {
1169    crate::formatting::extract_currency_code(key).is_some()
1170        || crate::formatting::extract_currency_code_micro(key).is_some()
1171        || crate::formatting::has_suffix_ci(key, "_jpy")
1172}
1173
1174/// How a `_url`-marked value compares to the shapes redaction handles.
1175enum UrlFieldCheck {
1176    Ok,
1177    NotAUrl,
1178    NotAString,
1179}
1180
1181/// Redaction gives URL treatment to string leaves and walks collections to
1182/// reach them, so the linter accepts the same shapes and checks the leaves.
1183fn url_field_violation(value: &Value) -> UrlFieldCheck {
1184    match value {
1185        Value::Null => UrlFieldCheck::Ok,
1186        Value::String(text) => {
1187            if is_wellformed_url_field(text) {
1188                UrlFieldCheck::Ok
1189            } else {
1190                UrlFieldCheck::NotAUrl
1191            }
1192        }
1193        Value::Array(items) => first_url_violation(items.iter()),
1194        Value::Object(entries) => first_url_violation(entries.values()),
1195        _ => UrlFieldCheck::NotAString,
1196    }
1197}
1198
1199fn first_url_violation<'value>(values: impl Iterator<Item = &'value Value>) -> UrlFieldCheck {
1200    for value in values {
1201        match url_field_violation(value) {
1202            UrlFieldCheck::Ok => {}
1203            violation => return violation,
1204        }
1205    }
1206    UrlFieldCheck::Ok
1207}
1208
1209fn is_wellformed_url_field(value: &str) -> bool {
1210    if is_scheme_prefixed_url(value) || is_scheme_prefixed_url(value.trim()) {
1211        return true;
1212    }
1213    !value.chars().any(char::is_whitespace) && !value.contains('@')
1214}
1215
1216fn is_scheme_prefixed_url(value: &str) -> bool {
1217    if value.bytes().any(|byte| byte.is_ascii_whitespace()) {
1218        return false;
1219    }
1220    let bytes = value.as_bytes();
1221    if !bytes.first().is_some_and(u8::is_ascii_alphabetic) {
1222        return false;
1223    }
1224    let mut index = 1;
1225    while index < bytes.len() {
1226        let character = bytes[index];
1227        if character.is_ascii_alphanumeric() || matches!(character, b'+' | b'-' | b'.') {
1228            index += 1;
1229        } else {
1230            break;
1231        }
1232    }
1233    value[index..].starts_with("://")
1234}
1235
1236fn join_pointer(base: &str, token: &str) -> String {
1237    let escaped = token.replace('~', "~0").replace('/', "~1");
1238    if base.is_empty() {
1239        format!("/{escaped}")
1240    } else {
1241        format!("{base}/{escaped}")
1242    }
1243}
1244
1245#[cfg(test)]
1246mod tests {
1247    use super::{
1248        LintOptions, LintSeverity, REGISTERED_SUFFIXES, RedactionCanaryError,
1249        assert_no_lint_findings, assert_redaction_canary_absent, assert_strict_event, lint_value,
1250    };
1251    use serde_json::{Value, json};
1252
1253    #[test]
1254    fn lint_fields_separately_from_their_values() {
1255        let options = LintOptions::default().runtime_values();
1256        let findings = super::lint_field_value("total_bytes", &json!([12, "8 MB"]), options);
1257        assert!(findings.iter().any(|finding| {
1258            finding.rule_id == "suffix_type_mismatch" && finding.pointer == "/1"
1259        }));
1260        let findings = assert_no_lint_findings(&json!({"rows": "1,200"})).unwrap_err();
1261        assert_eq!(findings[0].rule_id, "formatted_quantity_string");
1262        assert_eq!(findings[0].pointer, "/rows");
1263    }
1264
1265    #[test]
1266    fn public_lint_api_reports_and_filters_findings() {
1267        let value = json!({
1268            "timeout": 5,
1269            "size_bytes": "large",
1270            "created_rfc3339": "not-a-time"
1271        });
1272        let findings = lint_value(&value, LintOptions::default());
1273        assert_eq!(findings.len(), 3);
1274        assert!(
1275            findings
1276                .iter()
1277                .any(|finding| finding.severity == LintSeverity::Warning)
1278        );
1279        let errors = lint_value(&value, LintOptions::errors_only());
1280        assert_eq!(errors.len(), 2);
1281    }
1282
1283    #[test]
1284    fn integer_suffixes_accept_integral_decimals_and_signed_currency() {
1285        let value: Value = serde_json::from_str(
1286            r#"{
1287                "price_usd_cents": -1,
1288                "refund_eur_cents": -3.0,
1289                "size_bytes": 3.0,
1290                "created_epoch_ms": 3e0
1291            }"#,
1292        )
1293        .unwrap_or_else(|error| panic!("{error}"));
1294
1295        assert!(lint_value(&value, LintOptions::errors_only()).is_empty());
1296    }
1297
1298    #[test]
1299    fn registered_currency_suffixes_accept_three_or_four_letter_codes() {
1300        assert!(super::has_registered_suffix("fare_thb_cents"));
1301        assert!(super::has_registered_suffix("deposit_usdt_cents"));
1302        assert!(!super::has_registered_suffix("total_amount_cents"));
1303        assert!(!super::has_registered_suffix("price_usdtx_cents"));
1304    }
1305
1306    #[test]
1307    fn integer_suffixes_reject_fractional_values_and_negative_bytes() {
1308        let value: Value = serde_json::from_str(
1309            r#"{
1310                "price_usd_cents": 3.5,
1311                "size_bytes": -1
1312            }"#,
1313        )
1314        .unwrap_or_else(|error| panic!("{error}"));
1315        let findings = lint_value(&value, LintOptions::errors_only());
1316
1317        assert_eq!(
1318            findings
1319                .iter()
1320                .filter(|finding| finding.rule_id == "suffix_type_mismatch")
1321                .count(),
1322            2
1323        );
1324    }
1325
1326    #[test]
1327    fn unsafe_integer_finds_values_beyond_u128() {
1328        let value: Value =
1329            serde_json::from_str(r#"{"huge_count":340282366920938463463374607431768211456}"#)
1330                .unwrap_or_else(|error| panic!("{error}"));
1331        let findings = lint_value(&value, LintOptions::errors_only());
1332
1333        assert!(
1334            findings
1335                .iter()
1336                .any(|finding| finding.rule_id == "unsafe_integer"),
1337            "{findings:?}"
1338        );
1339    }
1340
1341    #[test]
1342    fn assertion_helpers_cover_protocol_lint_and_redaction() {
1343        let event = json!({
1344            "kind": "result",
1345            "result": {"code": "ready"},
1346            "trace": {}
1347        });
1348        assert!(assert_strict_event(&event).is_ok());
1349        assert!(assert_no_lint_findings(&event).is_ok());
1350        assert!(assert_redaction_canary_absent("{\"secret\":\"***\"}", "canary-42").is_ok());
1351        assert_eq!(
1352            assert_redaction_canary_absent("contains canary-42", "canary-42"),
1353            Err(RedactionCanaryError::Exposed)
1354        );
1355    }
1356
1357    /// The missing-suffix rule reads intent from the name, so what it stays
1358    /// quiet about matters as much as what it reports. Driven through the
1359    /// public entry point rather than the private helper, so a later move of
1360    /// the rule cannot take the pin with it.
1361    #[test]
1362    fn missing_suffix_reads_intent_from_the_name() {
1363        for (label, value) in [
1364            ("bare dimension name", json!({"timeout": 5000})),
1365            ("suffixed dimension name", json!({"request_timeout": 1})),
1366            ("_at timestamp", json!({"expires_at": 1})),
1367        ] {
1368            let findings = lint_value(&json!(value), LintOptions::default());
1369            assert!(
1370                findings.iter().any(|f| f.rule_id == "missing_suffix"),
1371                "{label}: expected a missing_suffix warning, got {findings:?}"
1372            );
1373        }
1374
1375        for (label, value) in [
1376            ("already labelled duration", json!({"timeout_ms": 5000})),
1377            ("already labelled currency", json!({"price_gbp_cents": 1})),
1378            ("already labelled secret", json!({"api_key_secret": "sk"})),
1379            // A dimension name over a container is a config block, not a bare
1380            // number. This is the guard that has no other test.
1381            (
1382                "dimension name over a container",
1383                json!({"timeout": {"connect": 1}}),
1384            ),
1385            ("credentials block", json!({"credentials": {"user": "x"}})),
1386            ("unrelated name", json!({"name": "demo"})),
1387        ] {
1388            let findings = lint_value(&json!(value), LintOptions::default());
1389            assert!(
1390                findings.is_empty(),
1391                "{label}: expected no findings, got {findings:?}"
1392            );
1393        }
1394    }
1395
1396    /// A canary is only useful if escaping cannot hide it. Every case here is a
1397    /// canary sitting verbatim in the output while a raw substring search
1398    /// misses it, which is how a leak used to pass this assertion.
1399    #[test]
1400    fn redaction_canary_survives_every_output_escape() {
1401        for (label, canary) in [
1402            (
1403                "pem newlines",
1404                "-----BEGIN KEY-----\nabc\n-----END KEY-----",
1405            ),
1406            ("double quote", "p@ss\"word"),
1407            ("backslash path", "C:\\Users\\me\\key"),
1408            ("tab", "a\tb"),
1409            ("non-bmp", "k\u{1f511}ey"),
1410        ] {
1411            let rendered = crate::render(
1412                &json!({ "note": canary }),
1413                crate::OutputFormat::Json,
1414                &crate::OutputOptions::default(),
1415            );
1416            assert!(
1417                rendered.contains("note"),
1418                "{label}: expected the field to survive rendering"
1419            );
1420            assert_eq!(
1421                assert_redaction_canary_absent(&rendered, canary),
1422                Err(RedactionCanaryError::Exposed),
1423                "{label}: escaped canary must still be reported, output was {rendered}"
1424            );
1425        }
1426    }
1427
1428    /// The percent-encoded spelling counts too: a canary can reach the stream
1429    /// through a URL without ever appearing literally.
1430    #[test]
1431    fn redaction_canary_is_found_percent_encoded() {
1432        assert_eq!(
1433            assert_redaction_canary_absent("{\"note\":\"https://h/p?q=a%20b%20c\"}", "a b c"),
1434            Err(RedactionCanaryError::Exposed)
1435        );
1436    }
1437
1438    #[test]
1439    fn redaction_canary_is_found_through_nested_and_mixed_encoding() {
1440        for serialized in [
1441            r#"{"note":"https://h/?next=https%3A%2F%2Fb%2F%3Fq%3D%2573ecret"}"#,
1442            r#"{"note":"\u002573ecret"}"#,
1443            r#"{"note":"%5Cu0073ecret"}"#,
1444            r#"{"note":"%255CuD83D%255CuDD11"}"#,
1445        ] {
1446            let canary = if serialized.contains("D83D") {
1447                "🔑"
1448            } else {
1449                "secret"
1450            };
1451            assert_eq!(
1452                assert_redaction_canary_absent(serialized, canary),
1453                Err(RedactionCanaryError::Exposed),
1454                "encoded output must still report the canary: {serialized}"
1455            );
1456        }
1457        assert_eq!(
1458            assert_redaction_canary_absent("%25not-a-canary", "secret"),
1459            Ok(())
1460        );
1461    }
1462
1463    #[test]
1464    fn redaction_canary_inspection_fails_closed_on_excessive_encoding_depth() {
1465        let ordinary = format!("%{}73afe", "25".repeat(15));
1466        assert_eq!(assert_redaction_canary_absent(&ordinary, "secret"), Ok(()));
1467        // No canary is present, but inspection may not silently pass an output
1468        // whose encoding cannot settle inside its fixed work budget.
1469        let deep = format!("%{}73afe{}", "25".repeat(1000), "x".repeat(4096));
1470        assert_eq!(
1471            assert_redaction_canary_absent(&deep, "secret"),
1472            Err(RedactionCanaryError::InspectionLimitExceeded)
1473        );
1474    }
1475
1476    /// The widened search must not cry wolf: a genuinely redacted secret
1477    /// reports clean in every format, whatever characters it contained.
1478    #[test]
1479    fn redaction_canary_stays_quiet_when_the_value_was_redacted() {
1480        for canary in [
1481            "-----BEGIN KEY-----\nabc\n-----END KEY-----",
1482            "p@ss\"word",
1483            "C:\\Users\\me\\key",
1484            "k\u{1f511}ey",
1485        ] {
1486            for format in [
1487                crate::OutputFormat::Json,
1488                crate::OutputFormat::Yaml,
1489                crate::OutputFormat::Plain,
1490            ] {
1491                let rendered = crate::render(
1492                    &json!({ "note_secret": canary }),
1493                    format,
1494                    &crate::OutputOptions::default(),
1495                );
1496                assert_eq!(
1497                    assert_redaction_canary_absent(&rendered, canary),
1498                    Ok(()),
1499                    "redacted output must not report a leak, output was {rendered}"
1500                );
1501            }
1502        }
1503    }
1504
1505    #[test]
1506    fn registry_suffixes_match_the_lint_table() {
1507        const REGISTRY: &str =
1508            include_str!("../../skills/agent-first-data/references/registry.json");
1509        let registry: Value =
1510            serde_json::from_str(REGISTRY).unwrap_or_else(|error| panic!("{error}"));
1511        let suffixes = registry["suffixes"]
1512            .as_array()
1513            .map(Vec::as_slice)
1514            .unwrap_or(&[]);
1515        let mut from_registry: Vec<(String, String)> = suffixes
1516            .iter()
1517            .filter_map(|entry| {
1518                Some((
1519                    entry["category"].as_str()?.to_string(),
1520                    entry["suffix"].as_str()?.to_string(),
1521                ))
1522            })
1523            .collect();
1524        let mut from_table: Vec<(String, String)> = REGISTERED_SUFFIXES
1525            .iter()
1526            .flat_map(|(category, suffixes)| {
1527                suffixes
1528                    .iter()
1529                    .map(move |suffix| ((*category).to_string(), (*suffix).to_string()))
1530            })
1531            .collect();
1532        from_registry.sort();
1533        from_table.sort();
1534        assert_eq!(from_table, from_registry);
1535    }
1536}