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