Skip to main content

deps_core/
parser.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use yaml_rust2::Event;
4use yaml_rust2::parser::{MarkedEventReceiver, Parser};
5use yaml_rust2::scanner::Marker;
6
7use crate::error::{DepsError, ParseFailureKind, Result};
8use crate::redact::RedactedUrl;
9
10/// Maximum allowed nesting depth for TOML table/array recursion before
11/// [`check_toml_nesting_depth`] rejects the input.
12///
13/// Counts both `[`/`{` bracket depth and dotted-key/table-header segment
14/// count (e.g. `a.b.c` or `[a.b.c]`), since both drive `toml-span`'s
15/// recursive descent.
16///
17/// This is a policy bound and defense-in-depth layer, not the only guard:
18/// `toml-span` 0.7.2 and later enforce their own native limit (128 levels,
19/// reported as `ErrorKind::ExceededDepthLimit`, which [`parse_toml_checked`]
20/// maps to [`CheckedTomlError::NestingTooDeep`]). The workspace requires
21/// `toml-span >= 0.7.2`, so that limit is the safety backstop against stack
22/// overflow, and this stricter pre-scan keeps the accepted range uniform
23/// across ecosystems and far above anything a real manifest needs: across a
24/// corpus of thousands of real-world `.toml` files, the deepest observed
25/// bracket nesting was 5 and the deepest dotted-key path was 6 segments.
26/// The upstream limit also counts dotted-key length, so its effective
27/// inline-table depth is about 64, nearly coinciding with this bound.
28///
29/// Historical note: `toml-span` 0.7.1 had no recursion limit, and a bisection
30/// on a 2 MiB stack (a `tokio` worker's default) showed a debug build
31/// surviving depth 220 for inline tables and 305 for arrays; 64 was chosen
32/// with a >3x margin under the tightest of those figures.
33pub const MAX_TOML_NESTING_DEPTH: usize = 64;
34
35/// Scans raw TOML text for table/array recursion deeper than `max_depth`.
36///
37/// `toml-span` has no public option to configure its recursion limit, so the
38/// stricter [`MAX_TOML_NESTING_DEPTH`] policy bound is enforced here, before
39/// the parser runs, as defense in depth on top of the parser's own native
40/// limit (`toml-span` 0.7.2 and later). This performs a single-pass
41/// structural scan — no actual parsing, so it cannot itself recurse or
42/// overflow — that bounds the two independent ways TOML content drives
43/// `toml-span`'s table/array recursion:
44///
45/// - **Bracket nesting**: `[`/`{` and `]`/`}` pairs, as in `[[[1]]]` or
46///   `{a={a=1}}`.
47/// - **Dotted-key/header segments**: each `.` in a dotted key (`a.b.c = 1`)
48///   or dotted table header (`[a.b.c]`) creates one level of table nesting
49///   with zero bracket characters, so bracket-only counting alone is not
50///   sufficient. Dots are only counted in *key* position (start of a
51///   top-level statement, inside a `[...]`/`[[...]]` header, or right after
52///   `{`/`,` while the innermost open bracket is `{`) — never in *value*
53///   position, so `a = 3.14` and multi-segment version/date values are not
54///   miscounted.
55///
56/// Both counts accumulate into one shared depth budget bounded by
57/// `max_depth`, since both are ways `toml-span` recurses. Bracket characters
58/// and dots inside string literals or line comments are skipped, so this
59/// does not misfire on values like `"flask[async]>=3.0"` or `# example:
60/// [1, 2]`. Both single-line (`"..."`, `'...'`, honoring `\"` escapes) and
61/// multi-line (`"""..."""`, `'''...'''`, including a body that legally ends
62/// with 1-2 extra literal quote characters before the closing delimiter, per
63/// the TOML spec) string forms are recognized, so brackets and dots inside a
64/// multi-line string body are never miscounted.
65///
66/// # Errors
67///
68/// Returns `Err(depth)` with the depth reached the instant nesting exceeds
69/// `max_depth`.
70///
71/// # Examples
72///
73/// ```
74/// use deps_core::parser::check_toml_nesting_depth;
75///
76/// assert!(check_toml_nesting_depth(r#"a = [1, 2, [3, 4]]"#, 4).is_ok());
77/// assert!(check_toml_nesting_depth("a = '''don't'''\nb = [1]", 4).is_ok());
78/// assert!(check_toml_nesting_depth("a = 3.14\nb.c = 1", 4).is_ok());
79///
80/// let deeply_nested = format!("a = {}1{}", "[".repeat(10), "]".repeat(10));
81/// assert_eq!(check_toml_nesting_depth(&deeply_nested, 4), Err(5));
82///
83/// let deep_dotted_key = format!("a{} = 1", ".a".repeat(10));
84/// assert_eq!(check_toml_nesting_depth(&deep_dotted_key, 4), Err(5));
85/// ```
86///
87/// See [`parse_toml_checked`] for the single entry point combining this guard with the
88/// actual `toml-span` parse.
89#[expect(
90    clippy::indexing_slicing,
91    reason = "every bytes[i] below is preceded by an i < len bounds check (loop condition or \
92              if guard); dot_frames[0] stays valid because it is the permanent first element \
93              of vec![0] and only ever popped while len() > 1"
94)]
95pub fn check_toml_nesting_depth(content: &str, max_depth: usize) -> std::result::Result<(), usize> {
96    let bytes = content.as_bytes();
97    let len = bytes.len();
98    let mut depth: usize = 0;
99    let mut i = 0;
100
101    // Bracket kinds currently open, used only to tell whether a `,` is
102    // inside an inline table (`{`, next token is a key) or an array (`[`,
103    // next token is a value).
104    let mut bracket_stack: Vec<u8> = Vec::new();
105    // Dot-segment counts not yet released, one frame per currently-open key
106    // context: index 0 is the persistent top-level-statement frame (reset at
107    // each top-level newline); further frames are pushed per open `{`.
108    let mut dot_frames: Vec<usize> = vec![0];
109    let mut in_key = true;
110
111    while i < len {
112        match bytes[i] {
113            b'#' => {
114                while i < len && bytes[i] != b'\n' {
115                    i += 1;
116                }
117            }
118            quote @ (b'"' | b'\'') => {
119                let is_multiline =
120                    bytes.get(i + 1) == Some(&quote) && bytes.get(i + 2) == Some(&quote);
121                i = if is_multiline {
122                    skip_multiline_string(bytes, i + 3, quote)
123                } else {
124                    skip_single_line_string(bytes, i + 1, quote)
125                };
126            }
127            b'{' => {
128                depth += 1;
129                if depth > max_depth {
130                    return Err(depth);
131                }
132                bracket_stack.push(b'{');
133                dot_frames.push(0);
134                in_key = true;
135                i += 1;
136            }
137            b'[' => {
138                depth += 1;
139                if depth > max_depth {
140                    return Err(depth);
141                }
142                bracket_stack.push(b'[');
143                i += 1;
144            }
145            b'}' => {
146                if dot_frames.len() > 1 {
147                    depth = depth.saturating_sub(dot_frames.pop().unwrap_or(0));
148                }
149                depth = depth.saturating_sub(1);
150                bracket_stack.pop();
151                in_key = false;
152                i += 1;
153            }
154            b']' => {
155                depth = depth.saturating_sub(1);
156                bracket_stack.pop();
157                i += 1;
158            }
159            b'.' if in_key => {
160                depth += 1;
161                if let Some(top) = dot_frames.last_mut() {
162                    *top += 1;
163                }
164                if depth > max_depth {
165                    return Err(depth);
166                }
167                i += 1;
168            }
169            b'=' if in_key => {
170                in_key = false;
171                i += 1;
172            }
173            b',' => {
174                match bracket_stack.last() {
175                    Some(b'{') => {
176                        if dot_frames.len() > 1 {
177                            depth = depth.saturating_sub(dot_frames.pop().unwrap_or(0));
178                        }
179                        dot_frames.push(0);
180                        in_key = true;
181                    }
182                    Some(b'[') => in_key = false,
183                    _ => {}
184                }
185                i += 1;
186            }
187            b'\n' => {
188                if bracket_stack.is_empty() {
189                    depth = depth.saturating_sub(dot_frames[0]);
190                    dot_frames[0] = 0;
191                    in_key = true;
192                }
193                i += 1;
194            }
195            _ => i += 1,
196        }
197    }
198
199    Ok(())
200}
201
202/// Which layer rejected a TOML document as nested too deeply.
203///
204/// Keeps the two origins distinguishable without a sentinel value: the
205/// pre-scan knows the depth it reached, while `toml-span`'s native limit does
206/// not expose one.
207///
208/// # Examples
209///
210/// ```
211/// use deps_core::parser::TomlDepthGuard;
212///
213/// assert_eq!(
214///     TomlDepthGuard::PreScan { depth: 65 }.to_string(),
215///     "array/table nesting depth 65 exceeds maximum of 64"
216/// );
217/// ```
218#[derive(Debug, Clone, Copy, PartialEq, Eq)]
219pub enum TomlDepthGuard {
220    /// [`check_toml_nesting_depth`] rejected the input before parsing.
221    PreScan {
222        /// The nesting depth reached the instant it exceeded [`MAX_TOML_NESTING_DEPTH`].
223        depth: usize,
224    },
225    /// `toml-span`'s own native depth limit rejected the input.
226    Parser,
227}
228
229impl fmt::Display for TomlDepthGuard {
230    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
231        match self {
232            Self::PreScan { depth } => write!(
233                f,
234                "array/table nesting depth {depth} exceeds maximum of {MAX_TOML_NESTING_DEPTH}"
235            ),
236            Self::Parser => {
237                f.write_str("array/table nesting exceeds the TOML parser's own depth limit")
238            }
239        }
240    }
241}
242
243/// Error returned by [`parse_toml_checked`]: either `content` nests too deeply
244/// (rejected by the [`MAX_TOML_NESTING_DEPTH`] pre-scan or by `toml-span`'s
245/// native depth limit) or `toml-span` rejects it as invalid syntax.
246///
247/// Distinct from a bare `toml_span::Error` so callers can branch on "too deep" vs.
248/// "malformed" without string-matching a message.
249#[derive(Debug, thiserror::Error)]
250pub enum CheckedTomlError {
251    /// `content` nests too deeply; `guard` records which layer rejected it.
252    #[error("{guard}")]
253    NestingTooDeep {
254        /// The layer that rejected the input, with its reached depth when known.
255        guard: TomlDepthGuard,
256    },
257    /// `content` passed the depth guards but `toml-span` rejected it as invalid TOML.
258    #[error(transparent)]
259    Syntax(toml_span::Error),
260}
261
262impl CheckedTomlError {
263    /// The [`ParseFailureKind`] this error maps to.
264    #[must_use]
265    pub const fn kind(&self) -> ParseFailureKind {
266        match self {
267            Self::NestingTooDeep { .. } => ParseFailureKind::NestingTooDeep,
268            Self::Syntax(_) => ParseFailureKind::Malformed,
269        }
270    }
271}
272
273fn classify_parse_error(error: toml_span::Error) -> CheckedTomlError {
274    // ErrorKind is not #[non_exhaustive] and gained this variant in a patch release, so a
275    // full match would break on `cargo update`; extract only the one variant we map.
276    if matches!(error.kind, toml_span::ErrorKind::ExceededDepthLimit) {
277        CheckedTomlError::NestingTooDeep {
278            guard: TomlDepthGuard::Parser,
279        }
280    } else {
281        CheckedTomlError::Syntax(error)
282    }
283}
284
285/// Parses `content` as TOML, first rejecting input whose nesting exceeds
286/// [`MAX_TOML_NESTING_DEPTH`] (see that constant's doc for why), and mapping
287/// `toml-span`'s own depth-limit error to the same error category.
288///
289/// The single shared entry point for every untrusted-TOML parse site in this workspace —
290/// collapses what would otherwise be a per-crate copy of [`check_toml_nesting_depth`] +
291/// `toml_span::parse` into one call.
292///
293/// # Errors
294///
295/// Returns [`CheckedTomlError::NestingTooDeep`] if `content` nests deeper than
296/// [`MAX_TOML_NESTING_DEPTH`] or exceeds `toml-span`'s native depth limit, or
297/// [`CheckedTomlError::Syntax`] if `toml-span` rejects `content` as invalid TOML.
298///
299/// # Examples
300///
301/// ```
302/// use deps_core::parser::{CheckedTomlError, parse_toml_checked};
303///
304/// assert!(parse_toml_checked("a = [1, 2, 3]").is_ok());
305///
306/// let deeply_nested = format!("a = {}1{}", "[".repeat(100), "]".repeat(100));
307/// assert!(matches!(
308///     parse_toml_checked(&deeply_nested),
309///     Err(CheckedTomlError::NestingTooDeep { .. })
310/// ));
311///
312/// assert!(matches!(parse_toml_checked("a = "), Err(CheckedTomlError::Syntax(_))));
313/// ```
314pub fn parse_toml_checked(
315    content: &str,
316) -> std::result::Result<toml_span::Value<'_>, CheckedTomlError> {
317    if let Err(depth) = check_toml_nesting_depth(content, MAX_TOML_NESTING_DEPTH) {
318        return Err(CheckedTomlError::NestingTooDeep {
319            guard: TomlDepthGuard::PreScan { depth },
320        });
321    }
322    toml_span::parse(content).map_err(classify_parse_error)
323}
324
325/// Advances past a single-line TOML string (`"..."` or `'...'`), returning
326/// the index just past its closing quote (or `bytes.len()` if unterminated —
327/// `toml_span` reports the real syntax error in that case, so it is safe for
328/// the rest of the file to be treated as string content here).
329#[expect(
330    clippy::indexing_slicing,
331    reason = "every bytes[i] below is preceded by an i < len bounds check"
332)]
333fn skip_single_line_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
334    let len = bytes.len();
335    while i < len {
336        if bytes[i] == b'\\' && quote == b'"' {
337            i += 2;
338            continue;
339        }
340        if bytes[i] == quote {
341            return i + 1;
342        }
343        i += 1;
344    }
345    i
346}
347
348/// Advances past a multi-line TOML string body (after its opening `"""`/`'''`),
349/// returning the index just past the closing delimiter.
350///
351/// Per the TOML spec, a multi-line basic string body may end with 1-2 literal
352/// quote characters immediately before the closing triple quote (e.g.
353/// `"""ends with "".""""` — content `ends with ""."`, then the closer). Any
354/// run of 3+ consecutive unescaped quote characters is therefore treated as
355/// the closing delimiter, regardless of how many of those quotes are "extra"
356/// literal content versus the delimiter itself — the distinction does not
357/// matter here since the whole run is consumed either way.
358#[expect(
359    clippy::indexing_slicing,
360    reason = "every bytes[i] below is preceded by an i < len bounds check"
361)]
362fn skip_multiline_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
363    let len = bytes.len();
364    while i < len {
365        if bytes[i] == b'\\' && quote == b'"' {
366            i += 2;
367            continue;
368        }
369        if bytes[i] == quote {
370            let run_start = i;
371            while i < len && bytes[i] == quote {
372                i += 1;
373            }
374            if i - run_start >= 3 {
375                return i;
376            }
377            continue;
378        }
379        i += 1;
380    }
381    i
382}
383
384/// Maximum allowed nesting depth for YAML block/flow recursion before
385/// [`check_yaml_nesting_depth`] rejects the input.
386///
387/// `yaml-rust2` 0.12's block-style (indentation-driven) sequence/mapping
388/// parser recurses once per nesting level with no depth limit (its flow-style
389/// `[[[...]]]` array parser already caps recursion, but block style and flow
390/// objects do not). A deeply nested `pubspec.yaml`/`pubspec.lock` can overflow
391/// the native thread stack and abort the whole process (SIGABRT) before
392/// `YamlLoader::load_from_str` ever returns an error. Unlike
393/// [`MAX_TOML_NESTING_DEPTH`] (which has an upstream backstop), this constant assumes the smallest stack any
394/// caller is likely to run on: a `tokio` worker thread's 2 MiB default, not
395/// `deps-lsp`'s own 8 MiB `WORKER_THREAD_STACK_SIZE` (defense-in-depth on top
396/// of this guard).
397///
398/// Bisected against the real `yaml-rust2` 0.12 recursion on a 2 MiB debug
399/// stack: the cheapest attack — compact block-sequence chaining
400/// (`- - - - 1`, 2 bytes per level) — survives depth 4535 and aborts at 4536;
401/// growing-indent block mappings (`k:\n k:\n  k:\n...`), the tightest case,
402/// survive depth 1993 and abort at 1994. 64 leaves a >30x margin under the
403/// tightest of these while still being far deeper than any real manifest
404/// needs — `pubspec.yaml`/`pubspec.lock` structures bottom out around 4-5
405/// levels (e.g. `packages.<name>.description.<field>`).
406pub const MAX_YAML_NESTING_DEPTH: usize = 64;
407
408/// Scans raw YAML text for block/flow recursion deeper than `max_depth`.
409///
410/// `YamlLoader::load_from_str` has no public option to cap recursion, so
411/// callers must reject pathological input before handing it to the parser.
412/// This performs a single-pass structural scan — no actual parsing, so it
413/// cannot itself recurse or overflow — that bounds the two independent ways
414/// YAML content drives `yaml-rust2`'s recursion:
415///
416/// - **Flow-style bracket nesting**: `[`/`{` and `]`/`}` pairs, as in
417///   `[[[1]]]` or `{a: {a: 1}}`.
418/// - **Block-style indentation**: each line whose leading indentation is
419///   deeper than the enclosing block context opens one nesting level (e.g. a
420///   mapping key or sequence item indented under its parent); each `-` in a
421///   compact chained sequence item (`- - - 1`) opens one level per dash,
422///   since it is equivalent to one nested single-item sequence per level.
423///
424/// Both counts accumulate into one shared depth budget bounded by
425/// `max_depth`. Line-start block indentation is scanned unconditionally on
426/// every line, even one that looks like a continuation of a still-open flow
427/// bracket from a previous line — an unclosed `[`/`{` must never be able to
428/// suppress scanning for the rest of the file (impl-critic C2), so this
429/// guard accepts occasionally over-counting a multi-line flow collection's
430/// continuation lines as extra block levels in exchange for never being able
431/// to go blind. A quote character is only treated as opening a quoted
432/// scalar when it sits at a token-start position (line start, or right
433/// after `: `, `- `, `[`, `{`, `,`) — never mid-token — so an apostrophe
434/// inside a plain scalar like `doesn't` is left alone rather than
435/// mistaken for the start of a string (impl-critic C1). Once a quoted
436/// scalar is opened, it is only ever trusted to close on the *same* line:
437/// hitting an unescaped `\n` before the matching quote resynchronizes the
438/// scanner at that newline unconditionally (including across a `\` right
439/// before it, which cannot extend the string past the line), rather than
440/// scanning forward indefinitely looking for a close — so neither a stray
441/// unquoted apostrophe nor a genuinely unterminated quoted scalar can ever
442/// blind the scanner to more than the remainder of one line. `#` outside a
443/// quoted scalar always starts a comment to end of line. Content indented
444/// under a literal/folded block scalar (`|`/`>`) is not specially exempted
445/// and is scanned like any other indentation, which can only make this
446/// guard *more* conservative, never less. Only ASCII space counts as
447/// indentation — a tab-indented line reads as indent 0, an assumption that
448/// currently holds only because `yaml-rust2` itself rejects tabs used for
449/// block indentation before recursing deep enough to matter.
450///
451/// # Errors
452///
453/// Returns `Err(depth)` with the depth reached the instant nesting exceeds
454/// `max_depth`.
455///
456/// # Examples
457///
458/// ```
459/// use deps_core::parser::check_yaml_nesting_depth;
460///
461/// assert!(check_yaml_nesting_depth("a:\n  b:\n    c: 1\n", 4).is_ok());
462///
463/// let deeply_nested = format!("{}1", "- ".repeat(10));
464/// assert!(check_yaml_nesting_depth(&deeply_nested, 4).is_err());
465///
466/// // An apostrophe mid-scalar must not blind the scanner to nesting later
467/// // in the file (impl-critic C1).
468/// let content = format!("a: it doesn't panic\n{}1", "- ".repeat(10));
469/// assert!(check_yaml_nesting_depth(&content, 4).is_err());
470/// ```
471#[expect(
472    clippy::indexing_slicing,
473    reason = "every bytes[i] below is preceded by an i < len bounds check (loop condition or \
474              if guard); single-pass byte scanner, see doc comment above"
475)]
476pub fn check_yaml_nesting_depth(content: &str, max_depth: usize) -> std::result::Result<(), usize> {
477    let bytes = content.as_bytes();
478    let len = bytes.len();
479    let mut depth: usize = 0;
480    let mut indent_stack: Vec<usize> = Vec::new();
481    let mut bracket_stack: Vec<u8> = Vec::new();
482
483    let mut i = 0;
484    while i < len {
485        let mut indent = 0;
486        while i < len && bytes[i] == b' ' {
487            indent += 1;
488            i += 1;
489        }
490        if i >= len || bytes[i] == b'\n' || bytes[i] == b'#' {
491            i = skip_to_eol(bytes, i);
492            if i < len && bytes[i] == b'\n' {
493                i += 1;
494            }
495            continue;
496        }
497
498        while indent_stack.last().is_some_and(|&top| top > indent) {
499            indent_stack.pop();
500            depth = depth.saturating_sub(1);
501        }
502
503        let mut col = indent;
504        while i < len && bytes[i] == b'-' && (i + 1 == len || matches!(bytes[i + 1], b' ' | b'\n'))
505        {
506            if indent_stack.last() != Some(&col) {
507                depth += 1;
508                if depth > max_depth {
509                    return Err(depth);
510                }
511                indent_stack.push(col);
512            }
513            i += 1;
514            col += 1;
515            while i < len && bytes[i] == b' ' {
516                i += 1;
517                col += 1;
518            }
519        }
520
521        if i < len && !matches!(bytes[i], b'\n' | b'#') && indent_stack.last() != Some(&col) {
522            depth += 1;
523            if depth > max_depth {
524                return Err(depth);
525            }
526            indent_stack.push(col);
527        }
528
529        // `prev` tracks whether the byte at `i` sits at a token-start
530        // position; starts `b' '` since we just consumed leading
531        // whitespace/dash-chain separators above.
532        let mut prev: u8 = b' ';
533        while i < len && bytes[i] != b'\n' {
534            match bytes[i] {
535                b'#' => {
536                    i = skip_to_eol(bytes, i);
537                    break;
538                }
539                quote @ (b'"' | b'\'')
540                    if matches!(prev, b' ' | b'\t' | b':' | b',' | b'[' | b'{' | b'-') =>
541                {
542                    i = skip_yaml_string(bytes, i + 1, quote);
543                    prev = quote;
544                }
545                b'[' | b'{' => {
546                    depth += 1;
547                    if depth > max_depth {
548                        return Err(depth);
549                    }
550                    bracket_stack.push(bytes[i]);
551                    prev = bytes[i];
552                    i += 1;
553                }
554                b']' | b'}' => {
555                    if bracket_stack.pop().is_some() {
556                        depth = depth.saturating_sub(1);
557                    }
558                    prev = bytes[i];
559                    i += 1;
560                }
561                b => {
562                    prev = b;
563                    i += 1;
564                }
565            }
566        }
567        if i < len && bytes[i] == b'\n' {
568            i += 1;
569        }
570    }
571
572    Ok(())
573}
574
575/// Advances past the rest of the current line (used for blank and comment
576/// lines), returning the index of the `\n` or `bytes.len()`.
577#[expect(
578    clippy::indexing_slicing,
579    reason = "every bytes[i] below is preceded by an i < len bounds check"
580)]
581fn skip_to_eol(bytes: &[u8], mut i: usize) -> usize {
582    let len = bytes.len();
583    while i < len && bytes[i] != b'\n' {
584        i += 1;
585    }
586    i
587}
588
589/// Advances past a YAML quoted scalar opened at a token-start position
590/// (`"..."` or `'...'`), returning the index just past its closing quote.
591///
592/// Only ever trusts a close on the *same* line: hits an unescaped `\n`
593/// before finding the matching quote, this returns the index of that
594/// newline unconsumed rather than continuing to search — so neither a
595/// genuinely unterminated quoted scalar nor a `\` placed right before the
596/// newline (which would otherwise "escape" it and extend the scan) can
597/// blind the caller's line-oriented scan to more than the current line
598/// (impl-critic C1). `yaml-rust2` reports the real syntax error for content
599/// this treats as unterminated. Handles double-quote backslash escapes and
600/// single-quote `''` escapes.
601#[expect(
602    clippy::indexing_slicing,
603    reason = "every bytes[i] below is preceded by an i < len bounds check"
604)]
605fn skip_yaml_string(bytes: &[u8], mut i: usize, quote: u8) -> usize {
606    let len = bytes.len();
607    while i < len && bytes[i] != b'\n' {
608        if bytes[i] == b'\\' && quote == b'"' {
609            if bytes.get(i + 1) == Some(&b'\n') {
610                break;
611            }
612            i += 2;
613            continue;
614        }
615        if bytes[i] == quote {
616            if quote == b'\'' && bytes.get(i + 1) == Some(&b'\'') {
617                i += 2;
618                continue;
619            }
620            return i + 1;
621        }
622        i += 1;
623    }
624    i
625}
626
627/// Renders a scalar YAML node as a string regardless of whether it was quoted or bare.
628///
629/// Covers `Yaml::String` (quoted) and `Yaml::Real`/`Yaml::Integer` (bare) —
630/// `yaml-rust2`'s `as_str` only matches `Yaml::String`, so an unquoted
631/// numeric-looking scalar (a bare `1.2` version range, or a two-component `version:
632/// 1.0`) would otherwise be silently treated as absent. Shared by every ecosystem
633/// that reads a YAML manifest/lockfile field that may legitimately be
634/// numeric-looking but unquoted (issue #721).
635///
636/// # Examples
637///
638/// ```
639/// use deps_core::yaml_scalar_string;
640/// use yaml_rust2::Yaml;
641///
642/// assert_eq!(yaml_scalar_string(&Yaml::String("1.2.3".into())), Some("1.2.3".to_string()));
643/// assert_eq!(yaml_scalar_string(&Yaml::Real("1.2".into())), Some("1.2".to_string()));
644/// assert_eq!(yaml_scalar_string(&Yaml::Integer(6)), Some("6".to_string()));
645/// assert_eq!(yaml_scalar_string(&Yaml::Boolean(true)), None);
646/// ```
647#[must_use]
648pub fn yaml_scalar_string(node: &yaml_rust2::Yaml) -> Option<String> {
649    match node {
650        yaml_rust2::Yaml::String(s) => Some(s.clone()),
651        yaml_rust2::Yaml::Real(s) => Some(s.clone()),
652        yaml_rust2::Yaml::Integer(i) => Some(i.to_string()),
653        _ => None,
654    }
655}
656
657/// Fixed per-node byte floor [`check_yaml_expansion`] charges for every
658/// `Yaml` node, on top of any heap content (e.g. a scalar's string bytes) it
659/// owns.
660///
661/// Derived from `size_of::<yaml_rust2::Yaml>()` itself (64 bytes on a 64-bit
662/// target as of `yaml-rust2` 0.12, dominated by the `String`/`Array`/`Hash`
663/// variants' inline pointer+len+cap fields plus the enum discriminant)
664/// rather than hardcoded, so a `yaml-rust2` layout change or a non-64-bit
665/// target cannot silently drift this out of sync with reality — the size of
666/// the value every `Yaml` node occupies wherever it is stored (a
667/// `Vec<Yaml>` element, a `Hash` entry, or a clone inside `anchor_map`),
668/// independent of its variant. This floor does *not* separately model every
669/// real cost `YamlLoader` incurs beyond it: `Hash`'s `LinkedHashMap`
670/// prev/next link pointers and hash-table slots, and `Vec`'s
671/// capacity-doubling slack, both add further real allocation on top of what
672/// this constant (and thus [`MAX_YAML_EXPANDED_BYTES`]) charges for — see
673/// that constant's doc for the measured size of that gap.
674const YAML_NODE_OVERHEAD_BYTES: u64 = size_of::<yaml_rust2::Yaml>() as u64;
675
676/// Maximum total byte weight [`check_yaml_expansion`] allows a document to
677/// expand to (counting anchor/alias-driven duplication) before rejecting it.
678///
679/// `yaml-rust2` 0.12's `YamlLoader::on_event_impl` deep-clones the whole
680/// anchored subtree once per `Event::Alias` reference (`anchor_map.get(&id)
681/// => v.clone()`), and again into `anchor_map` itself for every anchored
682/// node. Nesting depth (bounded by [`MAX_YAML_NESTING_DEPTH`]) is irrelevant
683/// to this: a shallow document with a handful of anchors, each aliased a
684/// handful of times, expands exponentially in the memory actually
685/// allocated. Critically, this must be a **byte** budget, not a node-count
686/// budget: a single large scalar anchor (e.g. a 1 MB string) aliased many
687/// times allocates megabytes per alias while costing only one node each, so
688/// a node-count budget lets it through cheaply — a document under 3 MB can
689/// exhaust hundreds of gigabytes this way. `YamlLoader` exposes no
690/// budget/config hook, so callers must reject pathological input before
691/// handing it to the loader.
692///
693/// `32 MiB` (`32 * 1024 * 1024` = 33,554,432) is the *charged* byte budget —
694/// not an exact bound on `YamlLoader`'s real peak allocation. Charged bytes
695/// track `YAML_NODE_OVERHEAD_BYTES`'s per-node floor plus scalar content,
696/// which undercounts two real costs that floor doesn't model: `Hash`'s
697/// `LinkedHashMap` prev/next link pointers and hash-table slots (hash-heavy
698/// documents, e.g. a `pubspec.lock`), and `String`/`Vec` capacity-doubling
699/// slack — the scanner builds every scalar via `String::new()` + repeated
700/// `push`, so a single large scalar whose length lands just past a
701/// power-of-two capacity boundary (e.g. 1,048,577 bytes) wastes nearly its
702/// own length again in unused capacity, and the same growth pattern applies
703/// to a `Vec` backing a long sequence. Measured with a counting allocator:
704/// real peak allocation runs about 1.16x-1.74x the charged total depending
705/// on document shape (steadier ~1.56x for hash-heavy lockfiles, up to ~2x
706/// for a large scalar or long sequence whose length lands right past a
707/// capacity-doubling boundary), so an accepted document charged right at
708/// this limit really allocates roughly 50-65 MB, not 32 MB. Bytes
709/// charged do not compound with nesting, so ~2x is the ceiling on that
710/// ratio, not a growing multiplier — the budget stays a bounded, linear
711/// function of input size either way, which is what actually matters for
712/// this guard (an *unbounded* multiplier, as with the pre-fix node-count
713/// budget's `O(2^depth)` blowup, is the failure mode this guards against).
714///
715/// Measured against real payloads (exact charged totals, reproducible
716/// against the shape scaled up from
717/// `test_check_yaml_expansion_few_hundred_package_lockfile_accepted`): a
718/// 1.9 MB / 12,500-package synthetic `pubspec.lock` charges 12,416,870 bytes
719/// (2.70x headroom); a 757 KB / 5,000-package one charges 4,961,870 bytes
720/// (6.76x headroom); the doubling-chain attack payload (see
721/// [`check_yaml_expansion`]'s doctest) charges 16,907,046 bytes at N=14
722/// (accepted) and 33,815,273 at N=15 (rejected, in well under a
723/// millisecond); and a single 1 MB anchor aliased 31 times (33,002,370
724/// bytes charged, ~1 MB source) is accepted while 32 times (34,002,434
725/// bytes) is rejected rather than allocating unboundedly.
726pub const MAX_YAML_EXPANDED_BYTES: usize = 32 * 1024 * 1024;
727
728/// Streams `content` through `yaml-rust2`'s own parser event stream and
729/// tallies the total bytes the `Yaml` nodes `YamlLoader::load_from_str`
730/// would allocate, rejecting once the tally exceeds `max_bytes`.
731///
732/// This is a pre-pass driven by the same `Parser`/event stream
733/// `YamlLoader::load_from_str` itself uses (`Parser::new(content.chars())`,
734/// `multi = true`), so anchor ids and event order are identical to the real
735/// load — unlike a raw-text `&anchor`/`*alias` scan, which was tried and
736/// rejected: ordinary prose such as `description: A widget *multiplier*
737/// helper` sits at exactly the position a text scanner treats as a token
738/// boundary, so it false-positives as an alias reference.
739///
740/// The accounting model mirrors `YamlLoader::on_event_impl` exactly, in
741/// bytes rather than node count: a `Scalar` charges
742/// `YAML_NODE_OVERHEAD_BYTES` plus its own string content length; a closed
743/// `Sequence`/`Mapping` charges `YAML_NODE_OVERHEAD_BYTES` for itself,
744/// plus the byte weight of its already-charged descendants. An anchored
745/// node (`SequenceStart`/`MappingStart`/`Scalar` anchor id `> 0`) charges
746/// its own subtree's byte weight a second time, mirroring
747/// `insert_new_node`'s `anchor_map.insert` clone; an `Alias` charges the
748/// referenced anchor's recorded byte weight (or
749/// `YAML_NODE_OVERHEAD_BYTES` for an unknown anchor id, matching the
750/// loader's own `Yaml::BadValue` fallback, which owns no heap content),
751/// mirroring the `v.clone()` in the `Event::Alias` arm. All counting uses
752/// `u64` with `saturating_add`, since the counter itself — not just the
753/// input — is the attack surface.
754///
755/// This pre-pass is not itself free relative to `max_bytes`: its own
756/// `anchors: BTreeMap<usize, u64>` grows by one entry per distinct anchor
757/// id seen, so a document built almost entirely of many tiny anchors (e.g.
758/// ~262,000 one-byte-scalar anchors, ~3.6 MB source) can transiently grow
759/// this map to roughly the same order of magnitude as `max_bytes` itself
760/// before the tally crosses it and rejection kicks in. This is bounded and
761/// transient, not unbounded like the vulnerability this guard closes, but
762/// callers should not assume the pre-pass's own peak memory is negligible
763/// next to the budget it enforces.
764///
765/// Any `ScanError` from this pre-pass is ignored: the real
766/// `YamlLoader::load_from_str` call that follows reports the authoritative
767/// syntax error. If the budget was already exceeded before the scan error,
768/// this still returns `Err`.
769///
770/// This pre-pass is, like the real load, driven by `Parser::load`'s mutually
771/// recursive `load_node`/`load_mapping`/`load_sequence` — callers must run
772/// [`check_yaml_nesting_depth`] first so this never recurses on input deep
773/// enough to overflow the stack itself.
774///
775/// # Errors
776///
777/// Returns `Err(bytes)` with the byte tally reached the instant it exceeds
778/// `max_bytes`.
779///
780/// # Examples
781///
782/// ```
783/// use deps_core::parser::check_yaml_expansion;
784///
785/// assert!(check_yaml_expansion("a: 1\nb: [2, 3]\n", 1000).is_ok());
786///
787/// // A widget *multiplier* helper is a plain scalar, not an alias.
788/// assert!(check_yaml_expansion("description: A widget *multiplier* helper", 1000).is_ok());
789///
790/// // Each anchor doubles the next one's alias count, so N levels expand to
791/// // roughly 2^N nodes from a source only ~2N bytes long.
792/// let mut doubling_chain = String::from("a0: &a0 [x, x]\n");
793/// for i in 1..20 {
794///     doubling_chain.push_str(&format!("a{i}: &a{i} [*a{prev}, *a{prev}]\n", prev = i - 1));
795/// }
796/// assert!(check_yaml_expansion(&doubling_chain, 1000).is_err());
797/// ```
798pub fn check_yaml_expansion(content: &str, max_bytes: usize) -> std::result::Result<(), usize> {
799    struct Receiver {
800        max: u64,
801        consumed: u64,
802        exceeded: bool,
803        stack: Vec<(usize, u64)>,
804        anchors: BTreeMap<usize, u64>,
805    }
806
807    impl Receiver {
808        fn charge(&mut self, n: u64) {
809            if self.exceeded {
810                return;
811            }
812            self.consumed = self.consumed.saturating_add(n);
813            if self.consumed > self.max {
814                self.exceeded = true;
815            }
816        }
817
818        /// Records a just-finished node's total subtree byte weight (`size`,
819        /// including itself): charges the anchor-clone cost and remembers
820        /// it for future aliases when `aid > 0`, then adds it to the
821        /// enclosing container's running subtree weight, if any.
822        fn finish(&mut self, size: u64, aid: usize) {
823            if self.exceeded {
824                return;
825            }
826            if aid > 0 {
827                self.charge(size);
828                self.anchors.insert(aid, size);
829            }
830            if let Some((_, parent_size)) = self.stack.last_mut() {
831                *parent_size = parent_size.saturating_add(size);
832            }
833        }
834    }
835
836    impl MarkedEventReceiver for Receiver {
837        fn on_event(&mut self, ev: Event, _mark: Marker) {
838            if self.exceeded {
839                return;
840            }
841            match ev {
842                Event::SequenceStart(aid, _) | Event::MappingStart(aid, _) => {
843                    self.stack.push((aid, 0));
844                }
845                Event::SequenceEnd | Event::MappingEnd => {
846                    if let Some((aid, children_size)) = self.stack.pop() {
847                        self.charge(YAML_NODE_OVERHEAD_BYTES);
848                        self.finish(children_size.saturating_add(YAML_NODE_OVERHEAD_BYTES), aid);
849                    }
850                }
851                Event::Scalar(ref v, _, aid, _) => {
852                    let size = YAML_NODE_OVERHEAD_BYTES.saturating_add(v.len() as u64);
853                    self.charge(size);
854                    self.finish(size, aid);
855                }
856                Event::Alias(id) => {
857                    let size = self
858                        .anchors
859                        .get(&id)
860                        .copied()
861                        .unwrap_or(YAML_NODE_OVERHEAD_BYTES);
862                    self.charge(size);
863                    self.finish(size, 0);
864                }
865                _ => {}
866            }
867        }
868    }
869
870    let mut recv = Receiver {
871        max: max_bytes as u64,
872        consumed: 0,
873        exceeded: false,
874        stack: Vec::new(),
875        anchors: BTreeMap::new(),
876    };
877
878    let _ = Parser::new(content.chars()).load(&mut recv, true);
879
880    if recv.exceeded {
881        Err(usize::try_from(recv.consumed).unwrap_or(usize::MAX))
882    } else {
883        Ok(())
884    }
885}
886
887/// Runs [`check_yaml_nesting_depth`] and [`check_yaml_expansion`] against `content`,
888/// converting either rejection into a [`DepsError::ParseError`] labeled with `file_type`.
889///
890/// The single shared entry point for every workspace call site that guards untrusted YAML
891/// before handing it to `yaml-rust2`'s real parser — collapses what would otherwise be a
892/// per-crate copy of both checks plus their `DepsError` construction (and the risk of the
893/// copies drifting in what they report) into one call.
894///
895/// # Errors
896///
897/// Returns [`DepsError::ParseError`] if `content` nests deeper than
898/// [`MAX_YAML_NESTING_DEPTH`] or would expand past [`MAX_YAML_EXPANDED_BYTES`].
899///
900/// # Examples
901///
902/// ```
903/// use deps_core::parser::check_yaml_bounds;
904///
905/// assert!(check_yaml_bounds("a:\n  b: 1\n", "example.yml").is_ok());
906///
907/// let deeply_nested = format!("{}1", "- ".repeat(100));
908/// let err = check_yaml_bounds(&deeply_nested, "example.yml").unwrap_err();
909/// assert!(err.to_string().contains("example.yml"));
910/// assert!(err.to_string().contains("nesting depth"));
911/// ```
912pub fn check_yaml_bounds(content: &str, file_type: &str) -> Result<()> {
913    if let Err(depth) = check_yaml_nesting_depth(content, MAX_YAML_NESTING_DEPTH) {
914        return Err(DepsError::parse_error_of_kind(
915            file_type,
916            ParseFailureKind::NestingTooDeep,
917            &format!("YAML nesting depth {depth} exceeds maximum of {MAX_YAML_NESTING_DEPTH}"),
918        ));
919    }
920    if let Err(bytes) = check_yaml_expansion(content, MAX_YAML_EXPANDED_BYTES) {
921        return Err(DepsError::parse_error(
922            file_type,
923            &format!(
924                "YAML expansion {bytes} bytes exceeds maximum of {MAX_YAML_EXPANDED_BYTES} bytes"
925            ),
926        ));
927    }
928    Ok(())
929}
930
931/// Maximum allowed nesting depth for JSON array/object recursion before
932/// [`check_json_nesting_depth`] rejects the input.
933///
934/// `serde_json` itself already caps recursion at a default depth of 128 for
935/// every container it enters — `deserialize_any`/`Value`, but equally
936/// `deserialize_seq`/`deserialize_map` (`check_recursion!` in its `de.rs`,
937/// guarding all three), so ordinary typed struct/`Vec` deserialization is
938/// covered exactly the same as parsing into a bare `Value`. This workspace
939/// never enables the `unbounded_depth` feature or calls
940/// `disable_recursion_limit`, so pathologically nested JSON cannot crash
941/// this workspace via stack overflow regardless of which of these paths a
942/// given call site uses. This guard is defense-in-depth, not a
943/// vulnerability fix: an early, cheap, byte-level rejection that fails
944/// faster and with a repo-specific error type than waiting for
945/// `serde_json`'s own limit, and keeps every untrusted-JSON parse site
946/// consistent with the [`MAX_TOML_NESTING_DEPTH`]/[`MAX_YAML_NESTING_DEPTH`]
947/// guards already applied to manifests of those formats. The depth is
948/// intentionally set narrower than `serde_json`'s built-in 128 — real
949/// payloads (OSV `database_specific`/`ecosystem_specific`, npm's `time` map,
950/// Packagist's `abandoned` field, ordinary `package.json`/`composer.json`
951/// manifests and lockfiles) never approach double digits of nesting, so 64
952/// is an arbitrary but generous ceiling chosen to match the existing
953/// TOML/YAML constants' value, not a stack-size bisection.
954pub const MAX_JSON_NESTING_DEPTH: usize = 64;
955
956/// Scans raw JSON bytes for `[`/`{` nesting deeper than `max_depth`, before
957/// handing the bytes to `serde_json::from_slice`/`from_str`.
958///
959/// A single-pass structural scan — no actual parsing, so it cannot itself
960/// recurse or overflow. String contents (JSON's only escaping construct) are
961/// tracked so bracket characters inside string literals are never
962/// miscounted as structural nesting. Multi-byte UTF-8 sequences are safe to
963/// scan byte-by-byte here: none of their continuation bytes collide with the
964/// ASCII structural characters this function looks for.
965///
966/// An unterminated (or truncated) string literal makes the scanner treat the
967/// rest of the buffer as string content and return `Ok`, undercounting any
968/// nesting that follows. This is safe: `serde_json` tokenizes the same bytes
969/// and will independently reject the identical malformed/truncated string
970/// (an EOF-while-parsing-string or similar syntax error) before its own
971/// recursive descent could ever reach nesting beyond what this scanner
972/// already counted up to the unterminated quote.
973///
974/// # Errors
975///
976/// Returns `Err(depth)` with the depth reached the instant nesting exceeds
977/// `max_depth`.
978///
979/// # Examples
980///
981/// ```
982/// use deps_core::parser::check_json_nesting_depth;
983///
984/// assert!(check_json_nesting_depth(br#"{"a":[1,2,{"b":3}]}"#, 4).is_ok());
985///
986/// let deeply_nested = format!("{}1{}", "[".repeat(10), "]".repeat(10));
987/// assert_eq!(check_json_nesting_depth(deeply_nested.as_bytes(), 4), Err(5));
988/// ```
989pub fn check_json_nesting_depth(
990    content: &[u8],
991    max_depth: usize,
992) -> std::result::Result<(), usize> {
993    let mut depth: usize = 0;
994    let mut in_string = false;
995    let mut escaped = false;
996
997    for &b in content {
998        if in_string {
999            if escaped {
1000                escaped = false;
1001            } else if b == b'\\' {
1002                escaped = true;
1003            } else if b == b'"' {
1004                in_string = false;
1005            }
1006            continue;
1007        }
1008        match b {
1009            b'"' => in_string = true,
1010            b'[' | b'{' => {
1011                depth += 1;
1012                if depth > max_depth {
1013                    return Err(depth);
1014                }
1015            }
1016            b']' | b'}' => depth = depth.saturating_sub(1),
1017            _ => {}
1018        }
1019    }
1020
1021    Ok(())
1022}
1023
1024/// Message text for a JSON payload rejected for nesting deeper than [`MAX_JSON_NESTING_DEPTH`].
1025///
1026/// The single shared wording for every workspace call site that rejects on JSON nesting depth,
1027/// whether it reports the rejection via [`CheckedJsonError`] (for [`parse_json_checked`]'s
1028/// callers) or via its own error type (a caller whose depth check runs
1029/// against an already-parsed AST rather than raw bytes, and so cannot route through
1030/// `parse_json_checked` itself, e.g. `deps-deno`'s `parse_deno_json`) — kept as one function so
1031/// the two paths cannot silently drift apart.
1032///
1033/// # Examples
1034///
1035/// ```
1036/// use deps_core::parser::json_depth_error_message;
1037///
1038/// assert_eq!(
1039///     json_depth_error_message(65),
1040///     "JSON nesting depth 65 exceeds maximum of 64"
1041/// );
1042/// ```
1043#[must_use]
1044pub fn json_depth_error_message(depth: usize) -> String {
1045    format!("JSON nesting depth {depth} exceeds maximum of {MAX_JSON_NESTING_DEPTH}")
1046}
1047
1048/// Error returned by [`parse_json_checked`]: either the payload nests deeper than
1049/// [`MAX_JSON_NESTING_DEPTH`] or `serde_json` rejects it.
1050///
1051/// Distinct from a bare `serde_json::Error` so callers can branch on "too deep" vs.
1052/// "malformed" without string-matching a message, mirroring [`CheckedTomlError`].
1053#[derive(Debug, thiserror::Error)]
1054pub enum CheckedJsonError {
1055    /// The payload nests deeper than [`MAX_JSON_NESTING_DEPTH`].
1056    #[error("{}", json_depth_error_message(*depth))]
1057    NestingTooDeep {
1058        /// Depth reached the instant the limit was exceeded.
1059        depth: usize,
1060    },
1061    /// The payload passed the depth guard but `serde_json` rejected it.
1062    #[error(transparent)]
1063    Syntax(serde_json::Error),
1064}
1065
1066impl CheckedJsonError {
1067    /// The [`ParseFailureKind`] this error maps to.
1068    #[must_use]
1069    pub const fn kind(&self) -> ParseFailureKind {
1070        match self {
1071            Self::NestingTooDeep { .. } => ParseFailureKind::NestingTooDeep,
1072            Self::Syntax(_) => ParseFailureKind::Malformed,
1073        }
1074    }
1075
1076    /// Flattens into a `serde_json::Error` for sites whose error type is fixed to it (for
1077    /// instance [`DepsError::ApiResponse`]); a depth rejection is synthesized via
1078    /// `serde::de::Error::custom`, indistinguishable from a `serde_json`-produced one.
1079    #[must_use]
1080    pub fn into_serde_json(self) -> serde_json::Error {
1081        match self {
1082            Self::NestingTooDeep { .. } => serde::de::Error::custom(self.to_string()),
1083            Self::Syntax(source) => source,
1084        }
1085    }
1086
1087    /// Converts into a [`DepsError`], naming `file_type` (for instance `"package.json"`) in a
1088    /// depth rejection's message. A depth rejection becomes [`DepsError::ParseError`] of kind
1089    /// [`ParseFailureKind::NestingTooDeep`]; a syntax error stays [`DepsError::Json`].
1090    #[must_use]
1091    pub fn into_deps_error(self, file_type: &str) -> DepsError {
1092        match self {
1093            Self::NestingTooDeep { .. } => {
1094                DepsError::parse_error_of_kind(file_type, self.kind(), &self)
1095            }
1096            Self::Syntax(source) => DepsError::Json(source),
1097        }
1098    }
1099}
1100
1101impl From<CheckedJsonError> for DepsError {
1102    /// Same as [`CheckedJsonError::into_deps_error`] with the generic file type `"JSON"`.
1103    fn from(error: CheckedJsonError) -> Self {
1104        error.into_deps_error("JSON")
1105    }
1106}
1107
1108/// Deserializes `bytes` into `T`, first rejecting payloads whose JSON nesting exceeds
1109/// [`MAX_JSON_NESTING_DEPTH`] (see that constant's doc for why).
1110///
1111/// The single shared entry point for every untrusted-JSON parse site in this workspace —
1112/// collapses what would otherwise be a per-crate copy of [`check_json_nesting_depth`] +
1113/// [`serde_json::from_slice`] into one call, and returns a [`CheckedJsonError`] that converts
1114/// into [`DepsError`] via `?`: a too-deep payload becomes a
1115/// [`ParseFailureKind::NestingTooDeep`] parse error, any other failure stays [`DepsError::Json`].
1116///
1117/// # Errors
1118///
1119/// Returns [`CheckedJsonError::NestingTooDeep`] if `bytes` nests deeper than
1120/// [`MAX_JSON_NESTING_DEPTH`], or [`CheckedJsonError::Syntax`] if `bytes` is not valid JSON
1121/// matching `T`.
1122///
1123/// # Examples
1124///
1125/// ```
1126/// use deps_core::parser::parse_json_checked;
1127///
1128/// let value: serde_json::Value = parse_json_checked(br#"{"a":1}"#).unwrap();
1129/// assert_eq!(value["a"], 1);
1130///
1131/// let deeply_nested = format!("{}1{}", "[".repeat(100), "]".repeat(100));
1132/// # use std::assert_matches;
1133/// assert_matches!(
1134///     parse_json_checked::<serde_json::Value>(deeply_nested.as_bytes()),
1135///     Err(deps_core::parser::CheckedJsonError::NestingTooDeep { .. })
1136/// );
1137/// ```
1138pub fn parse_json_checked<T: serde::de::DeserializeOwned>(
1139    bytes: &[u8],
1140) -> std::result::Result<T, CheckedJsonError> {
1141    if let Err(depth) = check_json_nesting_depth(bytes, MAX_JSON_NESTING_DEPTH) {
1142        return Err(CheckedJsonError::NestingTooDeep { depth });
1143    }
1144    serde_json::from_slice(bytes).map_err(CheckedJsonError::Syntax)
1145}
1146
1147/// Dependency source location (shared across all ecosystems).
1148///
1149/// Covers the union of all source types across Cargo, npm, PyPI, Go,
1150/// Dart, Bundler, Maven, and Gradle ecosystems.
1151#[derive(Clone, PartialEq, Eq, Hash)]
1152#[non_exhaustive]
1153pub enum DependencySource {
1154    /// Default package registry (crates.io, npm, PyPI, pub.dev, rubygems.org, Maven Central).
1155    Registry,
1156
1157    /// Git repository dependency.
1158    Git {
1159        /// Repository URL.
1160        url: String,
1161        /// Git ref: commit SHA, tag, or branch name (ecosystem-specific semantics).
1162        rev: Option<String>,
1163    },
1164
1165    /// Local filesystem path dependency.
1166    Path {
1167        /// Filesystem path, relative or absolute, as written in the manifest.
1168        path: String,
1169    },
1170
1171    /// Direct URL to artifact (PyPI wheels, npm tarballs).
1172    Url {
1173        /// URL the artifact is fetched from.
1174        url: String,
1175    },
1176
1177    /// SDK-provided dependency (Dart: `sdk: flutter`).
1178    Sdk {
1179        /// Name of the SDK providing this dependency.
1180        sdk: String,
1181    },
1182
1183    /// Workspace-inherited dependency (Cargo: `workspace = true`).
1184    Workspace,
1185
1186    /// Custom/alternative registry, named by an unresolved alias or raw index URL
1187    /// (Bundler custom sources, an unresolved Cargo `registry = "my-corp"`).
1188    ///
1189    /// This variant's meaning is unchanged by [`AlternateRegistry`](Self::AlternateRegistry)'s
1190    /// addition: it always means "not yet resolved to a concrete index this LSP can query" —
1191    /// `url` may hold a bare alias (`"my-corp"`) or a URL string, but never a value this LSP
1192    /// has validated and can fetch against. See [`AlternateRegistry`](Self::AlternateRegistry)
1193    /// for the resolved counterpart.
1194    ///
1195    /// `url` itself is stored raw (unresolved alias or a literal `registry-index`, possibly
1196    /// carrying `user:pass@` userinfo or a credential-bearing query string) — never redact
1197    /// this field in place, since `dedup_dependencies_by_source`'s collision check and other
1198    /// equality-based logic must keep comparing the real value. [`DependencySource`]'s own
1199    /// [`Debug`] impl redacts it via [`RedactedUrl`] before it can reach a log line; any
1200    /// future caller rendering `url` into hover/diagnostics text (currently latent — nothing
1201    /// does today) must redact it the same way rather than relying on `Debug` alone.
1202    CustomRegistry {
1203        /// Unresolved alias or raw index URL — redacted only when [`Debug`]-formatted (see
1204        /// the variant's own doc).
1205        url: String,
1206    },
1207
1208    /// A custom/alternative registry resolved to a concrete, fetchable index URL.
1209    ///
1210    /// Distinct from [`CustomRegistry`](Self::CustomRegistry) so "resolved" is a type-level
1211    /// state instead of string-sniffing an unresolved alias vs. a URL. Produced only by a
1212    /// parser that validated `index` against its own registry-configuration source (e.g.
1213    /// `deps-cargo`'s `.cargo/config.toml` resolution) — `deps-core` itself never constructs
1214    /// this variant. `index` is the `sparse+` prefix-stripped, https-only index URL —
1215    /// userinfo is rejected by `validate_index_url` before a URL can resolve to this variant,
1216    /// but a credential-bearing query string is not stripped there and CAN still be present
1217    /// (#935); [`DependencySource`]'s own [`Debug`] impl redacts `index` via [`RedactedUrl`]
1218    /// so a `tracing::warn!(?source, ...)` call site can never leak one. `index` is not
1219    /// itself an authorization decision — see the originating crate's config-resolution
1220    /// module for how (and whether) a request against it is authenticated.
1221    AlternateRegistry {
1222        /// The resolved index URL, validated and normalized by the originating parser —
1223        /// redacted only when [`Debug`]-formatted (see the variant's own doc).
1224        index: String,
1225        /// `true` exactly when this source serves content a public registry vouches for: a Cargo
1226        /// `[source.crates-io] replace-with` chain (`[source]` mirroring), or a Go `GOPROXY`
1227        /// chain verified by the public checksum database — as opposed to an explicit
1228        /// `registry`/`registry-index` naming a genuinely different, private registry.
1229        ///
1230        /// Affects **presentation and advisory gating only, never routing**: Cargo verifies
1231        /// per-version checksum equality against crates.io for a mirror, so its content is
1232        /// exactly as trustworthy as crates.io's own for vulnerability-scanning and hover-link
1233        /// purposes, even though the fetch itself still goes to `index`, not to crates.io.
1234        /// `deps-go` sets it for a `GOPROXY` chain with a URL hop when `GOSUMDB` is the public
1235        /// checksum database and `GOPRIVATE`/`GONOSUMDB` do not match the module.
1236        /// See [`crate::lsp_helpers::SourcePolicy::source_is_public_registry_content`].
1237        mirrors_public_registry: bool,
1238    },
1239}
1240
1241/// Hand-written, not derived (#935): a derived `Debug` would have printed `Git.url`,
1242/// `Url.url`, `CustomRegistry.url`, and `AlternateRegistry.index` raw — every one of them
1243/// can carry a credential (userinfo or a query-string secret) that never gets a chance to be
1244/// stripped, since none of these fields is validated/redacted before construction on every
1245/// code path (see [`DependencySource::AlternateRegistry`] and
1246/// [`DependencySource::CustomRegistry`]'s own docs). Any `tracing::warn!(?source, ...)` or
1247/// `{source:?}` call site — a common, idiomatic alternative to a hand-rolled `Display` — must
1248/// not be able to reopen this leak, so it is closed once here at the type level instead of at
1249/// each logging call site. Every variant and field is still shown (this is not a summary);
1250/// only URL-bearing field values are routed through [`RedactedUrl`] first.
1251impl fmt::Debug for DependencySource {
1252    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1253        match self {
1254            Self::Registry => f.write_str("Registry"),
1255            Self::Git { url, rev } => f
1256                .debug_struct("Git")
1257                .field("url", &RedactedUrl::new(url))
1258                .field("rev", rev)
1259                .finish(),
1260            Self::Path { path } => f.debug_struct("Path").field("path", path).finish(),
1261            Self::Url { url } => f
1262                .debug_struct("Url")
1263                .field("url", &RedactedUrl::new(url))
1264                .finish(),
1265            Self::Sdk { sdk } => f.debug_struct("Sdk").field("sdk", sdk).finish(),
1266            Self::Workspace => f.write_str("Workspace"),
1267            Self::CustomRegistry { url } => f
1268                .debug_struct("CustomRegistry")
1269                .field("url", &RedactedUrl::new(url))
1270                .finish(),
1271            Self::AlternateRegistry {
1272                index,
1273                mirrors_public_registry,
1274            } => f
1275                .debug_struct("AlternateRegistry")
1276                .field("index", &RedactedUrl::new(index))
1277                .field("mirrors_public_registry", mirrors_public_registry)
1278                .finish(),
1279        }
1280    }
1281}
1282
1283impl DependencySource {
1284    /// Returns true if this dependency comes from any registry (default or custom).
1285    ///
1286    /// Registry dependencies support version fetching and update checks.
1287    /// Git, Path, Url, Sdk, and Workspace dependencies do not.
1288    pub fn is_registry(&self) -> bool {
1289        matches!(
1290            self,
1291            Self::Registry | Self::CustomRegistry { .. } | Self::AlternateRegistry { .. }
1292        )
1293    }
1294
1295    /// Returns true if this LSP can resolve version data for this source
1296    /// against the registry client it actually queries.
1297    ///
1298    /// `Registry` resolves to the ecosystem's default public registry
1299    /// (crates.io, npm, PyPI, ...), which every `deps-*` crate implements a
1300    /// client for. `CustomRegistry` names a private/alternative registry
1301    /// (e.g. Bundler `source "https://gems.mycorp.com"`, Cargo
1302    /// `registry = "my-corp"`) that this LSP has no client for — known
1303    /// limitation, tracked until private-registry client support exists.
1304    /// Diagnostics and hover must not silently fall back to checking a
1305    /// `CustomRegistry` dependency's name against the *public* registry, so
1306    /// this deliberately diverges from `is_registry()` and returns `false`
1307    /// for it, alongside Git/Path/Url/Sdk/Workspace sources.
1308    ///
1309    /// Also `false` for `AlternateRegistry`, even though it is resolved: this method answers
1310    /// "does the generic `Registry` trait (crates.io-shaped, one client per ecosystem)
1311    /// resolve this", not "is version data reachable at all". An ecosystem whose registry
1312    /// implements per-source routing (`deps-cargo`'s `CargoRegistry`) must use
1313    /// [`crate::lsp_helpers::SourcePolicy::can_resolve_source`] instead, which defaults
1314    /// to this method and is the only override point — see that method's docs.
1315    pub fn is_version_resolvable(&self) -> bool {
1316        matches!(self, Self::Registry)
1317    }
1318}
1319
1320/// Whether `value` looks like a local filesystem path reference in a manifest specifier.
1321///
1322/// Matches a relative path (`./`, `../`), an absolute path (`/`), a home-relative path
1323/// (`~/`), or a Windows drive letter (`C:/`, `C:\`) — rather than a registry name, URL, or VCS
1324/// shorthand.
1325///
1326/// Shared by every ecosystem whose specifier grammar can name a local path with no explicit
1327/// `file:`/`path:`-style prefix at all (npm's bare relative-path dependency value, Go's
1328/// filesystem `replace` target) — previously duplicated near-verbatim between
1329/// `deps-npm`'s and `deps-go`'s parsers (code review #1202).
1330///
1331/// # Examples
1332///
1333/// ```
1334/// use deps_core::parser::looks_like_filesystem_path;
1335///
1336/// assert!(looks_like_filesystem_path("../local-sibling"));
1337/// assert!(looks_like_filesystem_path("~/local/sibling"));
1338/// assert!(looks_like_filesystem_path("C:/local/sibling"));
1339/// assert!(!looks_like_filesystem_path("github.com/acme/pkg"));
1340/// ```
1341#[must_use]
1342pub fn looks_like_filesystem_path(value: &str) -> bool {
1343    value.starts_with("./")
1344        || value.starts_with("../")
1345        || value.starts_with('/')
1346        || value.starts_with("~/")
1347        || (value
1348            .as_bytes()
1349            .first()
1350            .is_some_and(u8::is_ascii_alphabetic)
1351            && matches!(value.as_bytes().get(1), Some(b':')))
1352}
1353
1354/// Loading state for registry data fetching.
1355///
1356/// Tracks the current state of background registry operations to provide
1357/// user feedback about data availability.
1358///
1359/// # State Transitions
1360///
1361/// Complete state machine diagram showing all valid transitions:
1362///
1363/// ```text
1364///        ┌─────┐
1365///        │Idle │ (Initial state: no data loaded, not loading)
1366///        └──┬──┘
1367///           │
1368///           │ didOpen/didChange
1369///           │ (start fetching)
1370///           ▼
1371///      ┌────────┐
1372///      │Loading │ (Fetching registry data)
1373///      └───┬────┘
1374///          │
1375///          ├─────── Success ──────┐
1376///          │                       ▼
1377///          │                  ┌────────┐
1378///          │                  │Loaded  │ (Data cached and ready)
1379///          │                  └───┬────┘
1380///          │                      │
1381///          │                      │ didChange/refresh
1382///          │                      │ (re-fetch)
1383///          │                      │
1384///          │                      ▼
1385///          │                  ┌────────┐
1386///          │                  │Loading │
1387///          │                  └────────┘
1388///          │
1389///          └─────── Error ─────────┐
1390///                                   ▼
1391///                              ┌────────┐
1392///                              │Failed  │ (Fetch failed, old cache may exist)
1393///                              └───┬────┘
1394///                                  │
1395///                                  │ didChange/retry
1396///                                  │ (try again)
1397///                                  │
1398///                                  ▼
1399///                              ┌────────┐
1400///                              │Loading │
1401///                              └────────┘
1402/// ```
1403///
1404/// # Key Behaviors
1405///
1406/// - **Idle**: Initial state when no data has been fetched yet
1407/// - **Loading**: Actively fetching from registry (may show loading indicator)
1408/// - **Loaded**: Successfully fetched and cached data
1409/// - **Failed**: Network/registry error occurred (falls back to old cache if available)
1410///
1411/// # Thread Safety
1412///
1413/// This enum is `Copy` for efficient passing across thread boundaries in async contexts.
1414///
1415/// **Exhaustive** (issue #769): a closed UI state machine — a wildcard arm at any consuming
1416/// match site would silently render nothing for a new state instead of failing to compile.
1417#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
1418pub enum LoadingState {
1419    /// No data loaded, not currently loading
1420    #[default]
1421    Idle,
1422    /// Currently fetching registry data
1423    Loading,
1424    /// Data fetched and cached
1425    Loaded,
1426    /// Fetch failed (old cached data may still be available)
1427    Failed,
1428}
1429
1430/// Why [`deserialize_toml_checked`] rejected a document; the message is already redacted and
1431/// bounded when the error is built, so it is safe to log or show.
1432#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
1433pub enum TomlDeserializeError {
1434    /// The text is not valid TOML, or exceeds the nesting-depth limit.
1435    #[error("invalid TOML: {0}")]
1436    Toml(String),
1437    /// The TOML is valid but does not match the target type.
1438    #[error("invalid configuration: {0}")]
1439    Deserialize(String),
1440}
1441
1442/// Parses `content` as TOML under the nesting-depth guard and deserializes it into `T`.
1443///
1444/// Extracted from deps-cli's config loader so every TOML-backed operator file shares one
1445/// bounded, redacted path.
1446///
1447/// # Errors
1448///
1449/// [`TomlDeserializeError::Toml`] for a syntax or depth error,
1450/// [`TomlDeserializeError::Deserialize`] when the value does not fit `T`.
1451pub fn deserialize_toml_checked<T: serde::de::DeserializeOwned>(
1452    content: &str,
1453) -> std::result::Result<T, TomlDeserializeError> {
1454    let redact = |text: &str| crate::net_policy::redact_parse_error_for_log(text).into_owned();
1455    let value = parse_toml_checked(content)
1456        .map_err(|e| TomlDeserializeError::Toml(redact(&e.to_string())))?;
1457    let json = serde_json::to_value(&value)
1458        .map_err(|e| TomlDeserializeError::Deserialize(redact(&e.to_string())))?;
1459    serde_json::from_value(json)
1460        .map_err(|e| TomlDeserializeError::Deserialize(redact_type_mismatch(&e.to_string())))
1461}
1462
1463/// Redacts a `serde_json` deserialize message, and additionally drops the string payload of an
1464/// "invalid type/value: string ..." mismatch when credential redaction found nothing to
1465/// change: the offending value is operator-file content that has no reason to reach a log.
1466fn redact_type_mismatch(raw: &str) -> String {
1467    let redacted = crate::net_policy::redact_parse_error_for_log(raw);
1468    if !matches!(redacted, std::borrow::Cow::Borrowed(_)) {
1469        return redacted.into_owned();
1470    }
1471    const MARKERS: [&str; 2] = ["invalid type: string \"", "invalid value: string \""];
1472    // `rfind`: an escaped quote inside the payload also reads `\", expected `.
1473    const TAIL: &str = "\", expected ";
1474    for marker in MARKERS {
1475        if let Some(start) = raw.find(marker).map(|i| i + marker.len())
1476            && let Some(end) = raw.rfind(TAIL).filter(|end| *end >= start)
1477            && let (Some(head), Some(tail)) = (raw.get(..start), raw.get(end..))
1478        {
1479            return format!("{head}<redacted>{tail}");
1480        }
1481    }
1482    raw.to_owned()
1483}
1484
1485#[cfg(test)]
1486#[expect(
1487    clippy::cast_possible_truncation,
1488    reason = "#673: fixed test-fixture constants cast to usize never approach truncation range"
1489)]
1490mod tests {
1491    use super::*;
1492    use std::assert_matches;
1493
1494    #[test]
1495    fn test_check_toml_nesting_depth_empty_content() {
1496        assert_eq!(check_toml_nesting_depth("", 4), Ok(()));
1497    }
1498
1499    #[test]
1500    fn test_check_toml_nesting_depth_no_brackets() {
1501        assert_eq!(check_toml_nesting_depth("a = 1\nb = \"text\"\n", 4), Ok(()));
1502    }
1503
1504    #[test]
1505    fn test_check_toml_nesting_depth_exactly_at_max() {
1506        let content = format!("a = {}1{}", "[".repeat(4), "]".repeat(4));
1507        assert_eq!(check_toml_nesting_depth(&content, 4), Ok(()));
1508    }
1509
1510    #[test]
1511    fn test_check_toml_nesting_depth_one_over_max() {
1512        let content = format!("a = {}1{}", "[".repeat(5), "]".repeat(5));
1513        assert_eq!(check_toml_nesting_depth(&content, 4), Err(5));
1514    }
1515
1516    #[test]
1517    fn test_check_toml_nesting_depth_double_quoted_string_ignored() {
1518        let content = r#"a = "[[[[[unbalanced brackets]]]]]""#;
1519        assert_eq!(check_toml_nesting_depth(content, 0), Ok(()));
1520    }
1521
1522    #[test]
1523    fn test_check_toml_nesting_depth_single_quoted_string_ignored() {
1524        let content = "a = '[[[[[unbalanced brackets]]]]]'";
1525        assert_eq!(check_toml_nesting_depth(content, 0), Ok(()));
1526    }
1527
1528    #[test]
1529    fn test_check_toml_nesting_depth_escaped_quote_in_string() {
1530        // The escaped quote must not terminate the string early, so the
1531        // brackets that follow stay inside the string and are ignored.
1532        let content = r#"a = "embedded \" quote [[[[[""#;
1533        assert_eq!(check_toml_nesting_depth(content, 0), Ok(()));
1534    }
1535
1536    #[test]
1537    fn test_check_toml_nesting_depth_comment_ignored() {
1538        let content = "# [[[[[unbalanced comment brackets]]]]]\na = 1\n";
1539        assert_eq!(check_toml_nesting_depth(content, 0), Ok(()));
1540    }
1541
1542    #[test]
1543    fn test_check_toml_nesting_depth_mixed_array_and_table_nesting() {
1544        // [ { [ { -> depth 4 at the innermost brace.
1545        let content = "a = [{ b = [{ c = 1 }] }]";
1546        assert_eq!(check_toml_nesting_depth(content, 4), Ok(()));
1547        assert_eq!(check_toml_nesting_depth(content, 3), Err(4));
1548    }
1549
1550    #[test]
1551    fn test_check_toml_nesting_depth_inline_table_at_production_boundary() {
1552        // Nested inline tables (`{a={a=...}}`) are the shape that actually
1553        // exhausts a 2 MiB tokio worker stack before nested arrays do
1554        // (impl-critic C3) — exercise it against the real, shipped
1555        // `MAX_TOML_NESTING_DEPTH`, not just an arbitrary small max_depth.
1556        let depth = MAX_TOML_NESTING_DEPTH;
1557        let at_max = format!("a = {}1{}", "{a=".repeat(depth), "}".repeat(depth));
1558        assert_eq!(check_toml_nesting_depth(&at_max, depth), Ok(()));
1559
1560        let over_max = format!("a = {}1{}", "{a=".repeat(depth + 1), "}".repeat(depth + 1));
1561        assert_eq!(check_toml_nesting_depth(&over_max, depth), Err(depth + 1));
1562    }
1563
1564    #[test]
1565    fn test_check_toml_nesting_depth_dotted_header_at_production_boundary() {
1566        // Regression test for impl-critic C4: `[a.a.a...]` nests one table
1567        // level per `.` segment with zero bracket characters, so a
1568        // bracket-only scanner scores this depth 0 and lets it straight
1569        // through to `toml_span::parse`, which still stack-overflows.
1570        let depth = MAX_TOML_NESTING_DEPTH;
1571        let at_max = format!("[{}a]\ny = 1\n", "a.".repeat(depth - 1));
1572        assert_eq!(check_toml_nesting_depth(&at_max, depth), Ok(()));
1573
1574        let over_max = format!("[{}a]\ny = 1\n", "a.".repeat(depth));
1575        assert_eq!(check_toml_nesting_depth(&over_max, depth), Err(depth + 1));
1576    }
1577
1578    #[test]
1579    fn test_check_toml_nesting_depth_dotted_key_at_production_boundary() {
1580        // Same C4 bypass, via a dotted key (`a.a.a...= 1`) instead of a
1581        // dotted table header.
1582        let depth = MAX_TOML_NESTING_DEPTH;
1583        let at_max = format!("a{} = 1\n", ".a".repeat(depth));
1584        assert_eq!(check_toml_nesting_depth(&at_max, depth), Ok(()));
1585
1586        let over_max = format!("a{} = 1\n", ".a".repeat(depth + 1));
1587        assert_eq!(check_toml_nesting_depth(&over_max, depth), Err(depth + 1));
1588    }
1589
1590    #[test]
1591    fn test_check_toml_nesting_depth_legitimate_dotted_keys_accepted() {
1592        // Positive test: common, shallow legitimate dotted-key patterns must
1593        // never be rejected, and a float/version-like dot in value position
1594        // must never be miscounted as a key segment.
1595        let content = r#"
1596[tool.poetry.dependencies]
1597requests = { version = "^2.28", extras = ["socks"] }
1598
1599[libraries]
1600spring-boot = { module = "org.springframework.boot:spring-boot-starter", version.ref = "spring" }
1601
1602[metrics]
1603cpu_load = 3.14
1604"#;
1605        assert_eq!(
1606            check_toml_nesting_depth(content, MAX_TOML_NESTING_DEPTH),
1607            Ok(())
1608        );
1609    }
1610
1611    #[test]
1612    fn test_check_toml_nesting_depth_dotted_array_of_tables_header_at_boundary() {
1613        // `[[a.a...]]` double-bracket header: 2 bracket levels + N dot
1614        // segments must compose into one shared budget, not be tracked
1615        // independently (which would let brackets and dots each stay under
1616        // the cap while their sum exceeds it).
1617        let depth = MAX_TOML_NESTING_DEPTH;
1618        let at_max = format!("[[{}a]]\ny = 1\n", "a.".repeat(depth - 2));
1619        assert_eq!(check_toml_nesting_depth(&at_max, depth), Ok(()));
1620
1621        let over_max = format!("[[{}a]]\ny = 1\n", "a.".repeat(depth - 1));
1622        assert_eq!(check_toml_nesting_depth(&over_max, depth), Err(depth + 1));
1623    }
1624
1625    #[test]
1626    fn test_check_toml_nesting_depth_dotted_key_inside_bracket_header_composes() {
1627        // A `[a.b]` header followed by `c.d.e = {f.g = 1}` exercises bracket/dot accounting
1628        // across adjacent statements — the header's dots must not leak into the next
1629        // statement's budget.
1630        let content = "[a.b]\nc.d.e = {f.g = 1}\n";
1631        // Header peaks at depth 2 (1 bracket + 1 dot), released at its newline; the second
1632        // line peaks at depth 4 (2 dots for c.d.e + 1 for `{` + 1 for f.g's dot).
1633        assert_eq!(check_toml_nesting_depth(content, 4), Ok(()));
1634        assert_eq!(check_toml_nesting_depth(content, 3), Err(4));
1635    }
1636
1637    #[test]
1638    fn test_check_toml_nesting_depth_many_dotted_key_statements_do_not_accumulate() {
1639        // Hundreds of top-level dotted-key statements, each individually
1640        // well under the cap, must never accumulate across statements — a
1641        // per-key release that fired late (or not at all) would eventually
1642        // push a long file over the cap even though no single statement
1643        // does.
1644        let mut content = String::new();
1645        for i in 0..500 {
1646            content.push_str(&format!("k{i}.a.b.c = {i}\n"));
1647        }
1648        assert_eq!(check_toml_nesting_depth(&content, 4), Ok(()));
1649    }
1650
1651    #[test]
1652    fn test_check_toml_nesting_depth_sibling_inline_tables_in_array_do_not_accumulate() {
1653        // Many sibling `{ ... }` entries in one array, each with a short
1654        // dotted key, must not falsely accumulate depth across entries —
1655        // only one entry's dots are ever held at a time, matching how
1656        // `toml_span`'s recursion actually unwinds between array elements.
1657        let mut content = String::from("deps = [\n");
1658        for i in 0..200 {
1659            content.push_str(&format!(
1660                "  {{ name = \"pkg{i}\", version.ref = \"v\" }},\n"
1661            ));
1662        }
1663        content.push_str("]\n");
1664        assert_eq!(
1665            check_toml_nesting_depth(&content, MAX_TOML_NESTING_DEPTH),
1666            Ok(())
1667        );
1668    }
1669
1670    #[test]
1671    fn test_check_toml_nesting_depth_multiline_literal_odd_quote_count() {
1672        // A multi-line literal string containing an apostrophe (odd count of
1673        // its own quote char) must not desync the scanner into thinking the
1674        // string never closes.
1675        let content = format!("a = '''don't'''\nb = {}1{}", "[".repeat(5), "]".repeat(5));
1676        assert_eq!(check_toml_nesting_depth(&content, 4), Err(5));
1677    }
1678
1679    #[test]
1680    fn test_check_toml_nesting_depth_rejects_original_sigabrt_payloads() {
1681        // The exact payload shapes that reproduced the #150 SIGABRT even
1682        // after the first version of this guard shipped (impl-critic C1):
1683        // a multi-line string with an odd count of its own quote char,
1684        // followed by 20000-deep nesting.
1685        let n = 20_000;
1686        let payload1 = format!("a = '''don't'''\nb = {}1{}", "[".repeat(n), "]".repeat(n));
1687        let payload2 = format!(
1688            "a = \"\"\"x\"y\"\"\"\nb = {}1{}",
1689            "[".repeat(n),
1690            "]".repeat(n)
1691        );
1692
1693        assert!(check_toml_nesting_depth(&payload1, MAX_TOML_NESTING_DEPTH).is_err());
1694        assert!(check_toml_nesting_depth(&payload2, MAX_TOML_NESTING_DEPTH).is_err());
1695    }
1696
1697    #[test]
1698    fn test_check_toml_nesting_depth_multiline_basic_odd_quote_count() {
1699        let content = format!(
1700            "a = \"\"\"x\"y\"\"\"\nb = {}1{}",
1701            "[".repeat(5),
1702            "]".repeat(5)
1703        );
1704        assert_eq!(check_toml_nesting_depth(&content, 4), Err(5));
1705    }
1706
1707    #[test]
1708    fn test_check_toml_nesting_depth_multiline_basic_trailing_extra_quotes() {
1709        // TOML allows 1-2 literal quotes right before the closing triple
1710        // (here: 2 extra content quotes then the 3-quote closer, 5 in a
1711        // row). The scanner must still be back in normal mode right after,
1712        // so the nested array on the next line is counted correctly.
1713        let content = format!(
1714            "a = \"\"\"ends with two quotes: \"\"\"\"\"\nb = {}1{}",
1715            "[".repeat(5),
1716            "]".repeat(5)
1717        );
1718        assert_eq!(check_toml_nesting_depth(&content, 4), Err(5));
1719    }
1720
1721    #[test]
1722    fn test_check_toml_nesting_depth_brackets_inside_multiline_string_ignored() {
1723        let content = "d = \"\"\"\nsize is 5\" wide [[[unbalanced]]]\n\"\"\"\ne = 1\n";
1724        assert_eq!(check_toml_nesting_depth(content, 0), Ok(()));
1725    }
1726
1727    #[test]
1728    fn test_check_toml_nesting_depth_multiline_literal_brackets_ignored() {
1729        let content = "d = '''\n[[[unbalanced brackets]]]\n'''\ne = 1\n";
1730        assert_eq!(check_toml_nesting_depth(content, 0), Ok(()));
1731    }
1732
1733    #[test]
1734    fn test_check_toml_nesting_depth_multiline_basic_one_extra_trailing_quote() {
1735        // Exactly 1 extra content quote before the closing triple (4-quote
1736        // run total), between the 0-extra and 2-extra cases already covered.
1737        let content = format!(
1738            "a = \"\"\"ends with one quote: \"\"\"\"\nb = {}1{}",
1739            "[".repeat(5),
1740            "]".repeat(5)
1741        );
1742        assert_eq!(check_toml_nesting_depth(&content, 4), Err(5));
1743    }
1744
1745    #[test]
1746    fn test_check_toml_nesting_depth_adjacent_multiline_strings_then_nesting() {
1747        // Two separate multi-line strings (one basic, one literal) back to
1748        // back, each closing normally, must not leave the scanner desynced
1749        // for the real nesting that follows.
1750        let content = format!(
1751            "a = \"\"\"first\"\"\"\nb = '''second'''\nc = {}1{}",
1752            "[".repeat(5),
1753            "]".repeat(5)
1754        );
1755        assert_eq!(check_toml_nesting_depth(&content, 4), Err(5));
1756    }
1757
1758    #[test]
1759    fn test_parse_toml_checked_valid_document_ok() {
1760        let content = "a = [1, 2, { b = 3 }]";
1761        assert!(parse_toml_checked(content).is_ok());
1762    }
1763
1764    #[test]
1765    fn test_parse_toml_checked_over_depth_reports_nesting_too_deep() {
1766        let bracket_count = MAX_TOML_NESTING_DEPTH + 1;
1767        let content = format!(
1768            "a = {}1{}",
1769            "[".repeat(bracket_count),
1770            "]".repeat(bracket_count)
1771        );
1772        let err = parse_toml_checked(&content).unwrap_err();
1773        assert_matches!(
1774            err,
1775            CheckedTomlError::NestingTooDeep {
1776                guard: TomlDepthGuard::PreScan { depth }
1777            } if depth == bracket_count
1778        );
1779        assert_eq!(
1780            err.to_string(),
1781            format!(
1782                "array/table nesting depth {bracket_count} exceeds maximum of {MAX_TOML_NESTING_DEPTH}"
1783            )
1784        );
1785    }
1786
1787    fn nested_arrays(depth: usize) -> String {
1788        format!("a = {}1{}", "[".repeat(depth), "]".repeat(depth))
1789    }
1790
1791    #[test]
1792    fn test_parse_toml_checked_policy_band_rejected_by_pre_scan() {
1793        let content = nested_arrays(100);
1794        assert_matches!(
1795            parse_toml_checked(&content),
1796            Err(CheckedTomlError::NestingTooDeep {
1797                guard: TomlDepthGuard::PreScan { depth: 65 }
1798            })
1799        );
1800    }
1801
1802    #[test]
1803    fn test_upstream_toml_span_enforces_native_depth_limit_on_small_stack() {
1804        // Tripwire: fails if the resolved toml-span lacks its native depth limit
1805        // (< 0.7.2), which would leave the pre-scan as the only stack-overflow guard.
1806        let outcome = std::thread::Builder::new()
1807            .stack_size(2 * 1024 * 1024)
1808            .spawn(|| {
1809                let content = nested_arrays(200);
1810                toml_span::parse(&content).map(|_| ()).map_err(|e| e.kind)
1811            })
1812            .unwrap()
1813            .join()
1814            .expect("toml_span::parse must not overflow a 2 MiB stack at depth 200");
1815        assert_matches!(outcome, Err(toml_span::ErrorKind::ExceededDepthLimit));
1816    }
1817
1818    #[test]
1819    fn test_classify_parse_error_maps_upstream_depth_limit() {
1820        let error = toml_span::Error::from((
1821            toml_span::ErrorKind::ExceededDepthLimit,
1822            toml_span::Span::default(),
1823        ));
1824        assert_matches!(
1825            classify_parse_error(error),
1826            CheckedTomlError::NestingTooDeep {
1827                guard: TomlDepthGuard::Parser
1828            }
1829        );
1830    }
1831
1832    #[test]
1833    fn test_classify_parse_error_keeps_other_kinds_as_syntax() {
1834        let error = toml_span::parse("a = ").unwrap_err();
1835        assert_matches!(classify_parse_error(error), CheckedTomlError::Syntax(_));
1836    }
1837
1838    #[test]
1839    fn test_toml_depth_guard_parser_message_names_no_number() {
1840        let message = TomlDepthGuard::Parser.to_string();
1841        assert!(!message.chars().any(|c| c.is_ascii_digit()), "{message}");
1842    }
1843
1844    #[test]
1845    fn test_parse_toml_checked_syntax_error_matches_raw_toml_span_error() {
1846        let content = "a = ";
1847        let err = parse_toml_checked(content).unwrap_err();
1848        assert_matches!(err, CheckedTomlError::Syntax(_));
1849        assert_eq!(
1850            err.to_string(),
1851            toml_span::parse(content).unwrap_err().to_string()
1852        );
1853    }
1854
1855    /// Builds `n` lines of block mapping, each one column deeper than the
1856    /// last (`k:\n k:\n  k:\n...`) — the tightest real `yaml-rust2` crash
1857    /// shape (impl-critic/tester finding), and exactly `n` scanner pushes.
1858    fn nested_mapping(n: usize) -> String {
1859        let mut s = String::new();
1860        for i in 0..n {
1861            s.push_str(&" ".repeat(i));
1862            s.push_str("k:\n");
1863        }
1864        s
1865    }
1866
1867    #[test]
1868    fn test_check_yaml_nesting_depth_empty_content() {
1869        assert_eq!(check_yaml_nesting_depth("", 4), Ok(()));
1870    }
1871
1872    #[test]
1873    fn test_check_yaml_nesting_depth_no_nesting() {
1874        assert_eq!(
1875            check_yaml_nesting_depth("name: foo\nversion: 1.0.0\n", 1),
1876            Ok(())
1877        );
1878    }
1879
1880    #[test]
1881    fn test_check_yaml_nesting_depth_dash_chain_exactly_at_max() {
1882        // N dashes push N levels, plus one more for the trailing scalar's
1883        // own column (deeper than the last dash), so N=3 peaks at depth 4.
1884        let content = format!("{}1", "- ".repeat(3));
1885        assert_eq!(check_yaml_nesting_depth(&content, 4), Ok(()));
1886    }
1887
1888    #[test]
1889    fn test_check_yaml_nesting_depth_dash_chain_one_over_max() {
1890        let content = format!("{}1", "- ".repeat(4));
1891        assert_eq!(check_yaml_nesting_depth(&content, 4), Err(5));
1892    }
1893
1894    #[test]
1895    fn test_check_yaml_nesting_depth_block_mapping_exactly_at_max() {
1896        assert_eq!(check_yaml_nesting_depth(&nested_mapping(4), 4), Ok(()));
1897    }
1898
1899    #[test]
1900    fn test_check_yaml_nesting_depth_block_mapping_one_over_max() {
1901        assert_eq!(check_yaml_nesting_depth(&nested_mapping(5), 4), Err(5));
1902    }
1903
1904    #[test]
1905    fn test_check_yaml_nesting_depth_double_quoted_string_ignored() {
1906        let content = r#"a: "[[[[[unbalanced brackets]]]]]""#;
1907        assert_eq!(check_yaml_nesting_depth(content, 1), Ok(()));
1908    }
1909
1910    #[test]
1911    fn test_check_yaml_nesting_depth_single_quoted_string_ignored() {
1912        let content = "a: '[[[[[unbalanced brackets]]]]]'";
1913        assert_eq!(check_yaml_nesting_depth(content, 1), Ok(()));
1914    }
1915
1916    #[test]
1917    fn test_check_yaml_nesting_depth_escaped_quote_in_string() {
1918        // The escaped quote must not terminate the string early, so the
1919        // brackets that follow stay inside the string and are ignored.
1920        let content = r#"a: "embedded \" quote [[[[[""#;
1921        assert_eq!(check_yaml_nesting_depth(content, 1), Ok(()));
1922    }
1923
1924    #[test]
1925    fn test_check_yaml_nesting_depth_comment_ignored() {
1926        let content = "# [[[[[unbalanced comment brackets]]]]]\na: 1\n";
1927        assert_eq!(check_yaml_nesting_depth(content, 1), Ok(()));
1928    }
1929
1930    #[test]
1931    fn test_check_yaml_nesting_depth_mixed_flow_and_block_nesting() {
1932        // a: -> depth 1, "  b:" -> depth 2, then [ [ [ inside the value ->
1933        // peaks at depth 5 — flow and block share one budget.
1934        let content = "a:\n  b: [c, [d, [e]]]\n";
1935        assert_eq!(check_yaml_nesting_depth(content, 5), Ok(()));
1936        assert_eq!(check_yaml_nesting_depth(content, 4), Err(5));
1937    }
1938
1939    #[test]
1940    fn test_check_yaml_nesting_depth_dash_chain_at_production_boundary() {
1941        // N dashes plus the trailing scalar's own column peak at depth
1942        // N + 1, so N = depth - 1 is the boundary.
1943        let depth = MAX_YAML_NESTING_DEPTH;
1944        let at_max = format!("{}1", "- ".repeat(depth - 1));
1945        assert_eq!(check_yaml_nesting_depth(&at_max, depth), Ok(()));
1946
1947        let over_max = format!("{}1", "- ".repeat(depth));
1948        assert_eq!(check_yaml_nesting_depth(&over_max, depth), Err(depth + 1));
1949    }
1950
1951    #[test]
1952    fn test_check_yaml_nesting_depth_block_mapping_at_production_boundary() {
1953        let depth = MAX_YAML_NESTING_DEPTH;
1954        assert_eq!(
1955            check_yaml_nesting_depth(&nested_mapping(depth), depth),
1956            Ok(())
1957        );
1958        assert_eq!(
1959            check_yaml_nesting_depth(&nested_mapping(depth + 1), depth),
1960            Err(depth + 1)
1961        );
1962    }
1963
1964    #[test]
1965    fn test_check_yaml_nesting_depth_rejects_original_sigabrt_payloads() {
1966        // Depths comfortably past the empirically bisected real `yaml-rust2`
1967        // 0.12 crash thresholds on a 2 MiB debug stack (compact dash chain
1968        // aborts at 4536, growing-indent block mapping aborts at 1994) —
1969        // stays a real regression test even if `MAX_YAML_NESTING_DEPTH`
1970        // changes later, mirroring the TOML sibling test's margin.
1971        let dash_chain = format!("{}1", "- ".repeat(6000));
1972        assert!(check_yaml_nesting_depth(&dash_chain, MAX_YAML_NESTING_DEPTH).is_err());
1973
1974        let block_mapping = nested_mapping(2500);
1975        assert!(check_yaml_nesting_depth(&block_mapping, MAX_YAML_NESTING_DEPTH).is_err());
1976    }
1977
1978    #[test]
1979    fn test_check_yaml_nesting_depth_apostrophe_does_not_blind_scanner() {
1980        // impl-critic C1: an apostrophe mid-plain-scalar (e.g. `doesn't`)
1981        // must not be mistaken for opening a quoted scalar and swallow the
1982        // rest of the file, hiding the real nesting that follows.
1983        let payload = format!(
1984            "name: my_app\ndescription: A package that doesn't panic\n{}1",
1985            "- ".repeat(MAX_YAML_NESTING_DEPTH + 1)
1986        );
1987        assert!(check_yaml_nesting_depth(&payload, MAX_YAML_NESTING_DEPTH).is_err());
1988    }
1989
1990    #[test]
1991    fn test_check_yaml_nesting_depth_stray_double_quote_does_not_blind_scanner() {
1992        // Same root cause as above, with a stray `"` (e.g. a dimension
1993        // string like `6" long`) instead of an apostrophe.
1994        let payload = format!(
1995            "size: 6\" long\n{}1",
1996            "- ".repeat(MAX_YAML_NESTING_DEPTH + 1)
1997        );
1998        assert!(check_yaml_nesting_depth(&payload, MAX_YAML_NESTING_DEPTH).is_err());
1999    }
2000
2001    #[test]
2002    fn test_check_yaml_nesting_depth_unterminated_quote_only_blinds_one_line() {
2003        // A quote that genuinely never closes must resynchronize at the
2004        // next newline rather than scanning to EOF looking for a match.
2005        let payload = format!(
2006            "a: \"unterminated\n{}1",
2007            "- ".repeat(MAX_YAML_NESTING_DEPTH + 1)
2008        );
2009        assert!(check_yaml_nesting_depth(&payload, MAX_YAML_NESTING_DEPTH).is_err());
2010    }
2011
2012    #[test]
2013    fn test_check_yaml_nesting_depth_backslash_before_newline_does_not_extend_string() {
2014        // A `\` placed right before the line break must not "escape" the
2015        // newline and let an opened double-quoted scalar swallow further
2016        // lines (impl-critic C1 follow-up).
2017        let payload = format!(
2018            "a: \"unterminated\\\n{}1",
2019            "- ".repeat(MAX_YAML_NESTING_DEPTH + 1)
2020        );
2021        assert!(check_yaml_nesting_depth(&payload, MAX_YAML_NESTING_DEPTH).is_err());
2022    }
2023
2024    #[test]
2025    fn test_check_yaml_nesting_depth_unclosed_bracket_does_not_blind_scanner() {
2026        // impl-critic C2: an unclosed `[`/`{` must not permanently suppress
2027        // block-indentation scanning for the remainder of the file.
2028        let payload = format!("a: [\n{}1", "- ".repeat(MAX_YAML_NESTING_DEPTH + 1));
2029        assert!(check_yaml_nesting_depth(&payload, MAX_YAML_NESTING_DEPTH).is_err());
2030    }
2031
2032    #[test]
2033    fn test_check_yaml_nesting_depth_many_sibling_keys_do_not_accumulate() {
2034        let mut content = String::from("dependencies:\n");
2035        for i in 0..2000 {
2036            content.push_str(&format!("  pkg{i}: ^1.0.0\n"));
2037        }
2038        assert_eq!(check_yaml_nesting_depth(&content, 2), Ok(()));
2039    }
2040
2041    #[test]
2042    fn test_check_yaml_nesting_depth_multiline_flow_list_siblings_do_not_accumulate() {
2043        let mut content = String::from("dependencies: [\n");
2044        for _ in 0..2000 {
2045            content.push_str("  a,\n");
2046        }
2047        content.push_str("]\n");
2048        assert_eq!(check_yaml_nesting_depth(&content, 3), Ok(()));
2049    }
2050
2051    /// Billion-laughs-style doubling chain: depth stays 2, but expanded
2052    /// `Yaml` node count is roughly `2^n` from a source only ~20 bytes/level
2053    /// long — the exact attack shape from issue #175.
2054    fn doubling_chain(n: usize) -> String {
2055        let mut s = String::from("name: app\na0: &a0 [x, x]\n");
2056        for i in 1..=n {
2057            s.push_str(&format!("a{i}: &a{i} [*a{prev}, *a{prev}]\n", prev = i - 1));
2058        }
2059        s
2060    }
2061
2062    #[test]
2063    fn test_check_yaml_expansion_empty_content() {
2064        assert_eq!(check_yaml_expansion("", MAX_YAML_EXPANDED_BYTES), Ok(()));
2065    }
2066
2067    #[test]
2068    fn test_check_yaml_expansion_rejects_n30_doubling_chain_attack() {
2069        // The exact #175 payload shape: N=30 expands to over 2^30 nodes,
2070        // far past MAX_YAML_EXPANDED_BYTES, and must be rejected instead of
2071        // handed to `YamlLoader::load_from_str` (which OOMs/SIGKILLs).
2072        assert!(check_yaml_expansion(&doubling_chain(30), MAX_YAML_EXPANDED_BYTES).is_err());
2073    }
2074
2075    #[test]
2076    fn test_check_yaml_expansion_realistic_pubspec_yaml_accepted() {
2077        let yaml = r"
2078name: my_app
2079description: A sample app
2080environment:
2081  sdk: '>=3.0.0 <4.0.0'
2082dependencies:
2083  flutter:
2084    sdk: flutter
2085  http: ^1.0.0
2086  provider: ^6.0.0
2087  my_pkg:
2088    git:
2089      url: https://github.com/user/repo.git
2090      ref: main
2091      path: packages/my_pkg
2092dev_dependencies:
2093  build_runner: ^2.4.0
2094";
2095        assert_eq!(check_yaml_expansion(yaml, MAX_YAML_EXPANDED_BYTES), Ok(()));
2096    }
2097
2098    #[test]
2099    fn test_check_yaml_expansion_few_hundred_package_lockfile_accepted() {
2100        let mut lock = String::from("packages:\n");
2101        for i in 0..300 {
2102            lock.push_str(&format!(
2103                "  pkg_{i}:\n    dependency: \"direct main\"\n    description:\n      name: pkg_{i}\n      url: \"https://pub.dev\"\n    source: hosted\n    version: \"1.{i}.0\"\n"
2104            ));
2105        }
2106        assert_eq!(check_yaml_expansion(&lock, MAX_YAML_EXPANDED_BYTES), Ok(()));
2107    }
2108
2109    #[test]
2110    fn test_check_yaml_expansion_asterisk_in_plain_scalar_not_misread_as_alias() {
2111        // The raw-text pre-scan approach this algorithm replaced
2112        // false-positived on ordinary prose like this — a real `Event::Alias`
2113        // is never produced for a `*`/`&` inside a plain scalar value.
2114        let cases = [
2115            "description: A widget *multiplier* helper\n",
2116            "description: see *.dart files\n",
2117            "e: text &y more\n",
2118        ];
2119        for content in cases {
2120            assert_eq!(
2121                check_yaml_expansion(content, MAX_YAML_EXPANDED_BYTES),
2122                Ok(()),
2123                "false positive on: {content:?}"
2124            );
2125        }
2126    }
2127
2128    #[test]
2129    fn test_check_yaml_expansion_alias_to_undefined_anchor_accepted() {
2130        // `YamlLoader` itself falls back to `Yaml::BadValue` for an alias id
2131        // it has no anchor recorded for; this guard mirrors that fallback
2132        // (`unwrap_or(YAML_NODE_OVERHEAD_BYTES)`) rather than treating it as
2133        // unbounded.
2134        assert_eq!(
2135            check_yaml_expansion("a: *undefined\n", MAX_YAML_EXPANDED_BYTES),
2136            Ok(())
2137        );
2138    }
2139
2140    #[test]
2141    fn test_check_yaml_expansion_self_referential_alias_accepted() {
2142        // A sequence aliasing its own not-yet-closed anchor: the anchor
2143        // isn't registered yet when the alias event fires, so this hits the
2144        // same `unwrap_or(YAML_NODE_OVERHEAD_BYTES)` fallback as an
2145        // undefined anchor (verified against real `yaml-rust2` 0.12
2146        // behavior, not assumed) rather than recursing.
2147        assert_eq!(
2148            check_yaml_expansion("a: &x [1, *x]\n", MAX_YAML_EXPANDED_BYTES),
2149            Ok(())
2150        );
2151    }
2152
2153    #[test]
2154    fn test_check_yaml_expansion_at_production_boundary() {
2155        // `YAML_NODE_OVERHEAD_BYTES` is platform-dependent (`size_of::<yaml_rust2::Yaml>()`
2156        // shrinks on 32-bit targets), so the level that crosses `MAX_YAML_EXPANDED_BYTES`
2157        // shifts by platform — find the real boundary empirically instead of hardcoding a
2158        // 64-bit-specific N.
2159        let boundary = (1..=25)
2160            .find(|&n| check_yaml_expansion(&doubling_chain(n), MAX_YAML_EXPANDED_BYTES).is_err())
2161            .expect("doubling chain must cross MAX_YAML_EXPANDED_BYTES well within 25 levels");
2162
2163        assert_eq!(
2164            check_yaml_expansion(&doubling_chain(boundary - 1), MAX_YAML_EXPANDED_BYTES),
2165            Ok(()),
2166            "level {} (just before the boundary) should stay under budget",
2167            boundary - 1
2168        );
2169        assert!(check_yaml_expansion(&doubling_chain(boundary), MAX_YAML_EXPANDED_BYTES).is_err());
2170    }
2171
2172    #[test]
2173    fn test_check_yaml_expansion_large_scalar_anchor_aliased_many_times_rejected() {
2174        // Critic CRITICAL 1: a node-count budget accepted a large-scalar anchor aliased many
2175        // times (node growth is linear, but memory grows with anchor size x alias count) — a
2176        // 1 MB anchor aliased 32 times is ~33 MB of real `YamlLoader` allocation, only 34
2177        // nodes.
2178        let anchor_value = "A".repeat(1_000_000);
2179        let mut content = format!("s: &s \"{anchor_value}\"\nl:\n");
2180        for _ in 0..32 {
2181            content.push_str("  - *s\n");
2182        }
2183        assert!(check_yaml_expansion(&content, MAX_YAML_EXPANDED_BYTES).is_err());
2184    }
2185
2186    #[test]
2187    fn test_check_yaml_expansion_exact_max_boundary() {
2188        // `charge` compares with `>`, so a document whose total charge is
2189        // exactly `max_bytes` must be accepted, and one byte more must be
2190        // rejected — pins that this is intentional (an accidental `>=`
2191        // would reject the exact-max case and go uncaught otherwise).
2192        let scalar_len = 1000usize;
2193        let max_bytes = YAML_NODE_OVERHEAD_BYTES as usize + scalar_len;
2194        let content = "a".repeat(scalar_len);
2195
2196        assert_eq!(check_yaml_expansion(&content, max_bytes), Ok(()));
2197        assert!(check_yaml_expansion(&content, max_bytes - 1).is_err());
2198    }
2199
2200    #[test]
2201    fn test_check_yaml_expansion_matches_recursive_byte_weight_oracle() {
2202        // Pins the invariant the whole design rests on: `check_yaml_expansion`'s
2203        // streaming tally equals an independent, recursive byte-weight
2204        // computation over the real parsed `Yaml` tree, for anchor-free
2205        // docs. Catches an accidental algorithm regression, or a
2206        // `yaml-rust2` upgrade that changes what gets allocated, that unit
2207        // tests on fixed payloads alone would not.
2208        fn recursive_weight(y: &yaml_rust2::Yaml) -> u64 {
2209            match y {
2210                yaml_rust2::Yaml::String(s) => YAML_NODE_OVERHEAD_BYTES + s.len() as u64,
2211                yaml_rust2::Yaml::Array(arr) => {
2212                    YAML_NODE_OVERHEAD_BYTES + arr.iter().map(recursive_weight).sum::<u64>()
2213                }
2214                yaml_rust2::Yaml::Hash(h) => {
2215                    YAML_NODE_OVERHEAD_BYTES
2216                        + h.iter()
2217                            .map(|(k, v)| recursive_weight(k) + recursive_weight(v))
2218                            .sum::<u64>()
2219                }
2220                _ => YAML_NODE_OVERHEAD_BYTES,
2221            }
2222        }
2223
2224        // Binary search for the smallest `max_bytes` that `check_yaml_expansion`
2225        // still accepts — since `charge` uses `>`, this is exactly the real
2226        // total charged.
2227        fn smallest_accepted(content: &str) -> u64 {
2228            let (mut lo, mut hi) = (0u64, 1_000_000u64);
2229            while lo < hi {
2230                let mid = lo + (hi - lo) / 2;
2231                if check_yaml_expansion(content, usize::try_from(mid).unwrap_or(usize::MAX)).is_ok()
2232                {
2233                    hi = mid;
2234                } else {
2235                    lo = mid + 1;
2236                }
2237            }
2238            lo
2239        }
2240
2241        // All scalars quoted, so every leaf is `Yaml::String` and its
2242        // parsed length matches its source text exactly (an unquoted
2243        // integer/bool/null scalar's `Yaml` variant does not retain its
2244        // source text, which would make the oracle inexact).
2245        let docs = [
2246            r#"a: "hello""#,
2247            r#"a: ["x", "yy", "zzz"]"#,
2248            "a:\n  b: \"value\"\n  c:\n    - \"one\"\n    - \"two\"\n",
2249        ];
2250
2251        for content in docs {
2252            let parsed = yaml_rust2::YamlLoader::load_from_str(content).unwrap();
2253            let expected = recursive_weight(&parsed[0]);
2254            assert_eq!(
2255                smallest_accepted(content),
2256                expected,
2257                "oracle mismatch for {content:?}"
2258            );
2259        }
2260    }
2261
2262    #[test]
2263    fn test_check_yaml_bounds_depth_rejection_is_nesting_too_deep() {
2264        let content = format!("{}1", "- ".repeat(MAX_YAML_NESTING_DEPTH + 1));
2265        let err = check_yaml_bounds(&content, "example.yml").expect_err("must be rejected");
2266        assert_eq!(
2267            err.parse_failure_kind(),
2268            Some(ParseFailureKind::NestingTooDeep)
2269        );
2270    }
2271
2272    #[test]
2273    fn test_checked_toml_error_kind_maps_each_variant() {
2274        let too_deep = format!("a = {}1{}", "[".repeat(100), "]".repeat(100));
2275        let Err(deep) = parse_toml_checked(&too_deep) else {
2276            panic!("expected a depth rejection");
2277        };
2278        assert_eq!(deep.kind(), ParseFailureKind::NestingTooDeep);
2279        let Err(syntax) = parse_toml_checked("a = ") else {
2280            panic!("expected a syntax error");
2281        };
2282        assert_eq!(syntax.kind(), ParseFailureKind::Malformed);
2283    }
2284
2285    #[test]
2286    fn test_parse_failure_kind_is_none_for_non_parse_errors() {
2287        let io = DepsError::Io(std::io::Error::other("disk"));
2288        assert_eq!(io.parse_failure_kind(), None);
2289        assert_eq!(
2290            DepsError::parse_error("x", &"bad").parse_failure_kind(),
2291            Some(ParseFailureKind::Malformed)
2292        );
2293    }
2294
2295    #[test]
2296    fn test_check_yaml_bounds_within_limits_ok() {
2297        assert!(check_yaml_bounds("a:\n  b: 1\n", "example.yml").is_ok());
2298    }
2299
2300    #[test]
2301    fn test_check_yaml_bounds_nesting_exceeded_reports_depth_message() {
2302        let content = format!("{}1", "- ".repeat(MAX_YAML_NESTING_DEPTH + 1));
2303        // Cross-checked against the oracle rather than hardcoded, in case depth accounting changes.
2304        let expected_depth = check_yaml_nesting_depth(&content, MAX_YAML_NESTING_DEPTH)
2305            .expect_err("fixture should already exceed the nesting-depth budget");
2306
2307        let err = check_yaml_bounds(&content, "example.yml")
2308            .expect_err("expected the nesting-depth guard to reject this");
2309        let DepsError::ParseError {
2310            file_type, source, ..
2311        } = err
2312        else {
2313            panic!("expected DepsError::ParseError");
2314        };
2315        assert_eq!(file_type, "example.yml");
2316        assert_eq!(
2317            source.to_string(),
2318            format!(
2319                "YAML nesting depth {expected_depth} exceeds maximum of {MAX_YAML_NESTING_DEPTH}"
2320            )
2321        );
2322    }
2323
2324    #[test]
2325    fn test_check_yaml_bounds_expansion_exceeded_reports_expansion_message() {
2326        let mut content = String::from("a0: &a0 [x, x]\n");
2327        for i in 1..=20 {
2328            content.push_str(&format!("a{i}: &a{i} [*a{prev}, *a{prev}]\n", prev = i - 1));
2329        }
2330        let expected_bytes = check_yaml_expansion(&content, MAX_YAML_EXPANDED_BYTES)
2331            .expect_err("fixture should already exceed the expansion budget");
2332
2333        let err = check_yaml_bounds(&content, "example.yml")
2334            .expect_err("expected the expansion budget to reject this");
2335        let DepsError::ParseError {
2336            file_type, source, ..
2337        } = err
2338        else {
2339            panic!("expected DepsError::ParseError");
2340        };
2341        assert_eq!(file_type, "example.yml");
2342        assert_eq!(
2343            source.to_string(),
2344            format!(
2345                "YAML expansion {expected_bytes} bytes exceeds maximum of {MAX_YAML_EXPANDED_BYTES} bytes"
2346            )
2347        );
2348    }
2349
2350    #[test]
2351    fn test_dependency_source_registry() {
2352        let source = DependencySource::Registry;
2353        assert_eq!(source, DependencySource::Registry);
2354        assert!(source.is_registry());
2355        assert!(source.is_version_resolvable());
2356    }
2357
2358    #[test]
2359    fn test_dependency_source_git() {
2360        let source = DependencySource::Git {
2361            url: "https://github.com/user/repo".into(),
2362            rev: Some("main".into()),
2363        };
2364
2365        assert!(!source.is_registry());
2366        assert!(!source.is_version_resolvable());
2367
2368        match source {
2369            DependencySource::Git { url, rev } => {
2370                assert_eq!(url, "https://github.com/user/repo");
2371                assert_eq!(rev, Some("main".into()));
2372            }
2373            _ => panic!("Expected Git source"),
2374        }
2375    }
2376
2377    #[test]
2378    fn test_dependency_source_git_no_rev() {
2379        let source = DependencySource::Git {
2380            url: "https://github.com/user/repo".into(),
2381            rev: None,
2382        };
2383
2384        match source {
2385            DependencySource::Git { url, rev } => {
2386                assert_eq!(url, "https://github.com/user/repo");
2387                assert!(rev.is_none());
2388            }
2389            _ => panic!("Expected Git source"),
2390        }
2391    }
2392
2393    #[test]
2394    fn test_dependency_source_path() {
2395        let source = DependencySource::Path {
2396            path: "../local-crate".into(),
2397        };
2398
2399        assert!(!source.is_registry());
2400
2401        match source {
2402            DependencySource::Path { path } => {
2403                assert_eq!(path, "../local-crate");
2404            }
2405            _ => panic!("Expected Path source"),
2406        }
2407    }
2408
2409    #[test]
2410    fn test_dependency_source_url() {
2411        let source = DependencySource::Url {
2412            url: "https://example.com/package.whl".into(),
2413        };
2414        assert!(!source.is_registry());
2415        assert!(!source.is_version_resolvable());
2416    }
2417
2418    #[test]
2419    fn test_dependency_source_sdk() {
2420        let source = DependencySource::Sdk {
2421            sdk: "flutter".into(),
2422        };
2423        assert!(!source.is_registry());
2424    }
2425
2426    #[test]
2427    fn test_dependency_source_workspace() {
2428        let source = DependencySource::Workspace;
2429        assert!(!source.is_registry());
2430        assert!(!source.is_version_resolvable());
2431    }
2432
2433    #[test]
2434    fn test_dependency_source_custom_registry() {
2435        let source = DependencySource::CustomRegistry {
2436            url: "https://gems.example.com".into(),
2437        };
2438        // `is_registry()` stays true (it does name a registry), but this LSP
2439        // has no client for a private/custom registry, so it must not be
2440        // treated as version-resolvable against the public registry (#248).
2441        assert!(source.is_registry());
2442        assert!(!source.is_version_resolvable());
2443    }
2444
2445    #[test]
2446    fn test_dependency_source_debug_redacts_custom_registry_userinfo() {
2447        let source = DependencySource::CustomRegistry {
2448            url: "https://user:hunter2@gems.example.com/simple".into(),
2449        };
2450        let debug_output = format!("{source:?}");
2451        assert!(!debug_output.contains("hunter2"), "{debug_output}");
2452        assert!(debug_output.contains("gems.example.com"), "{debug_output}");
2453        assert!(debug_output.contains("/simple"), "{debug_output}");
2454    }
2455
2456    #[test]
2457    fn test_dependency_source_debug_redacts_alternate_registry_query_string() {
2458        let source = DependencySource::AlternateRegistry {
2459            index: "https://index.mycorp.dev/api?api_key=SECRET".into(),
2460            mirrors_public_registry: false,
2461        };
2462        let debug_output = format!("{source:?}");
2463        assert!(!debug_output.contains("SECRET"), "{debug_output}");
2464        assert!(debug_output.contains("index.mycorp.dev"), "{debug_output}");
2465        assert!(debug_output.contains("/api"), "{debug_output}");
2466    }
2467
2468    #[test]
2469    fn test_dependency_source_alternate_registry() {
2470        let source = DependencySource::AlternateRegistry {
2471            index: "https://index.mycorp.dev".into(),
2472            mirrors_public_registry: false,
2473        };
2474        // `is_registry()` is true (it is a registry, just not the default one), but
2475        // the generic `Registry` trait still can't resolve it — only an ecosystem
2476        // whose `EcosystemFormatter::can_resolve_source` override understands this
2477        // variant (e.g. `deps-cargo`'s `CargoFormatter`) can.
2478        assert!(source.is_registry());
2479        assert!(!source.is_version_resolvable());
2480    }
2481
2482    #[test]
2483    fn test_check_json_nesting_depth_shallow_accepted() {
2484        let content = br#"{"a":[1,2,{"b":3}],"c":"[not{real}nesting]"}"#;
2485        assert_eq!(check_json_nesting_depth(content, 4), Ok(()));
2486    }
2487
2488    #[test]
2489    fn test_check_json_nesting_depth_string_brackets_ignored() {
2490        // Brackets inside a string literal (including an escaped quote) must
2491        // never be counted as structural nesting.
2492        let content = br#"{"a":"[[[[[\"]]]]]"}"#;
2493        assert_eq!(check_json_nesting_depth(content, 1), Ok(()));
2494    }
2495
2496    #[test]
2497    fn test_check_json_nesting_depth_mixed_array_and_object_nesting() {
2498        let content = br#"[{"a":[{"b":1}]}]"#;
2499        assert_eq!(check_json_nesting_depth(content, 4), Ok(()));
2500        assert_eq!(check_json_nesting_depth(content, 3), Err(4));
2501    }
2502
2503    #[test]
2504    fn test_check_json_nesting_depth_deeply_nested_array_rejected() {
2505        // The #430 attack shape: without this guard, `serde_json::from_slice`
2506        // would still not crash — it independently halts at its own default
2507        // recursion limit (128) with a clean `Err`. This guard rejects the
2508        // same shape earlier, at a stricter depth (64), with a repo-specific
2509        // `check_json_nesting_depth` error rather than a `serde_json::Error`.
2510        let deeply_nested = format!("{}1{}", "[".repeat(10), "]".repeat(10));
2511        assert_eq!(
2512            check_json_nesting_depth(deeply_nested.as_bytes(), 4),
2513            Err(5)
2514        );
2515    }
2516
2517    #[test]
2518    fn test_check_json_nesting_depth_unterminated_string_blinds_scanner_but_serde_json_still_rejects()
2519     {
2520        // An unterminated `"` makes the scanner treat everything after it as
2521        // string content, so it returns `Ok` even with deep nesting past the
2522        // quote. This is safe only because `serde_json` independently halts
2523        // on the same malformed input via its own tokenizer.
2524        let payload = format!("\"unterminated{}1", "[".repeat(MAX_JSON_NESTING_DEPTH + 1));
2525        assert_eq!(
2526            check_json_nesting_depth(payload.as_bytes(), MAX_JSON_NESTING_DEPTH),
2527            Ok(())
2528        );
2529        assert!(serde_json::from_str::<serde_json::Value>(&payload).is_err());
2530    }
2531
2532    #[test]
2533    fn test_check_json_nesting_depth_at_production_boundary() {
2534        let depth = MAX_JSON_NESTING_DEPTH;
2535        let at_max = format!("{}1{}", "[".repeat(depth), "]".repeat(depth));
2536        assert_eq!(check_json_nesting_depth(at_max.as_bytes(), depth), Ok(()));
2537
2538        let over_max = format!("{}1{}", "[".repeat(depth + 1), "]".repeat(depth + 1));
2539        assert_eq!(
2540            check_json_nesting_depth(over_max.as_bytes(), depth),
2541            Err(depth + 1)
2542        );
2543    }
2544
2545    #[test]
2546    fn test_checked_json_error_kind_maps_each_variant() {
2547        let depth = MAX_JSON_NESTING_DEPTH + 1;
2548        let deep = format!("{}1{}", "[".repeat(depth), "]".repeat(depth));
2549        let Err(too_deep) = parse_json_checked::<serde_json::Value>(deep.as_bytes()) else {
2550            panic!("expected a depth rejection");
2551        };
2552        assert_matches!(
2553            too_deep,
2554            CheckedJsonError::NestingTooDeep { depth: d } if d == depth
2555        );
2556        assert_eq!(too_deep.kind(), ParseFailureKind::NestingTooDeep);
2557        let from_deep = DepsError::from(too_deep);
2558        assert_eq!(
2559            from_deep.parse_failure_kind(),
2560            Some(ParseFailureKind::NestingTooDeep)
2561        );
2562
2563        let Err(syntax) = parse_json_checked::<serde_json::Value>(b"{bad}") else {
2564            panic!("expected a syntax error");
2565        };
2566        assert_eq!(syntax.kind(), ParseFailureKind::Malformed);
2567        assert_matches!(DepsError::from(syntax), DepsError::Json(_));
2568    }
2569
2570    #[test]
2571    fn test_parse_json_checked_boundary_at_max_depth() {
2572        let at_max = format!(
2573            "{}1{}",
2574            "[".repeat(MAX_JSON_NESTING_DEPTH),
2575            "]".repeat(MAX_JSON_NESTING_DEPTH)
2576        );
2577        assert!(parse_json_checked::<serde_json::Value>(at_max.as_bytes()).is_ok());
2578
2579        let over = MAX_JSON_NESTING_DEPTH + 1;
2580        let over_max = format!("{}1{}", "[".repeat(over), "]".repeat(over));
2581        assert_matches!(
2582            parse_json_checked::<serde_json::Value>(over_max.as_bytes()),
2583            Err(CheckedJsonError::NestingTooDeep { depth }) if depth == over
2584        );
2585    }
2586
2587    #[test]
2588    fn test_checked_json_error_into_deps_error_names_file_type() {
2589        let err = CheckedJsonError::NestingTooDeep { depth: 65 }.into_deps_error("package.json");
2590        assert!(err.to_string().contains("package.json"));
2591        assert_eq!(
2592            err.parse_failure_kind(),
2593            Some(ParseFailureKind::NestingTooDeep)
2594        );
2595    }
2596
2597    #[test]
2598    fn test_checked_json_error_into_serde_json_keeps_depth_message() {
2599        let err = CheckedJsonError::NestingTooDeep { depth: 65 };
2600        assert_eq!(
2601            err.into_serde_json().to_string(),
2602            json_depth_error_message(65)
2603        );
2604    }
2605
2606    #[test]
2607    fn test_dependency_source_debug() {
2608        let source = DependencySource::Registry;
2609        let debug = format!("{:?}", source);
2610        assert_eq!(debug, "Registry");
2611
2612        let git = DependencySource::Git {
2613            url: "https://example.com".into(),
2614            rev: Some("main".into()),
2615        };
2616        let git_debug = format!("{:?}", git);
2617        assert!(git_debug.contains("https://example.com"));
2618        assert!(git_debug.contains("main"));
2619    }
2620
2621    #[test]
2622    fn test_loading_state_default() {
2623        assert_eq!(LoadingState::default(), LoadingState::Idle);
2624    }
2625
2626    #[test]
2627    fn test_loading_state_all_variants() {
2628        let variants = [
2629            LoadingState::Idle,
2630            LoadingState::Loading,
2631            LoadingState::Loaded,
2632            LoadingState::Failed,
2633        ];
2634        for (i, v1) in variants.iter().enumerate() {
2635            for (j, v2) in variants.iter().enumerate() {
2636                if i == j {
2637                    assert_eq!(v1, v2);
2638                } else {
2639                    assert_ne!(v1, v2);
2640                }
2641            }
2642        }
2643    }
2644
2645    // #673: property tests for the depth/expansion checkers shared by all 14 ecosystem
2646    // crates — complements the `fuzz/` corpus (which explores much longer runs but isn't
2647    // part of `cargo test`) with a fast, CI-covered "never panics" gate over arbitrary
2648    // input, not just the hand-picked cases above.
2649    mod proptests {
2650        use super::*;
2651        use proptest::prelude::*;
2652
2653        proptest! {
2654            // #673 S3: generates `String` directly rather than random `Vec<u8>` gated on
2655            // `str::from_utf8`, which almost never reaches the function under test. Proptest's
2656            // default `\PC*` excludes control chars including `\n`, which would skip the
2657            // newline-only paths (`dot_frames[0]` reset, YAML block-style scanning) — `\n`/`\t`
2658            // are added back into the character class to keep those paths in play.
2659            #[test]
2660            fn check_toml_nesting_depth_never_panics(text in "(?s)[\\PC\\n\\t]{0,256}") {
2661                let _ = check_toml_nesting_depth(&text, MAX_TOML_NESTING_DEPTH);
2662            }
2663
2664            #[test]
2665            fn check_yaml_nesting_depth_never_panics(text in "(?s)[\\PC\\n\\t]{0,256}") {
2666                let _ = check_yaml_nesting_depth(&text, MAX_YAML_NESTING_DEPTH);
2667            }
2668
2669            #[test]
2670            fn check_yaml_expansion_never_panics(text in any::<String>()) {
2671                let _ = check_yaml_expansion(&text, MAX_YAML_EXPANDED_BYTES);
2672            }
2673
2674            #[test]
2675            fn check_json_nesting_depth_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..4096)) {
2676                let _ = check_json_nesting_depth(&bytes, MAX_JSON_NESTING_DEPTH);
2677            }
2678
2679            #[test]
2680            fn parse_json_checked_never_panics(bytes in proptest::collection::vec(any::<u8>(), 0..4096)) {
2681                let _ = parse_json_checked::<serde_json::Value>(&bytes);
2682            }
2683        }
2684    }
2685}