rust-yaml 1.1.0

A fast, safe YAML 1.2 library for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
//! Tests for security resource limits

use rust_yaml::{Limits, LoaderType, Yaml, YamlConfig};

fn permissive_with_alias_cap(cap: usize) -> Limits {
    Limits {
        max_total_alias_nodes: cap,
        ..Limits::permissive()
    }
}

#[test]
fn test_max_depth_limit() {
    // Create a YAML with excessive nesting
    let mut yaml_str = String::new();
    for _ in 0..60 {
        yaml_str.push_str("- ");
    }
    yaml_str.push_str("value");

    // Test with strict limits
    let config = YamlConfig {
        limits: Limits::strict(), // max_depth = 50
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&yaml_str);

    assert!(result.is_err());
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("depth") || error_str.contains("limit"),
            "Expected depth limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_max_string_length_limit() {
    // Create a YAML with a long string that exceeds the limit
    let long_string = "x".repeat(70_000); // 70KB string (above 64KB limit)
    let yaml_str = format!("key: \"{}\"", long_string);

    // Test with strict limits (max string = 64KB)
    let config = YamlConfig {
        limits: Limits::strict(),
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&yaml_str);

    assert!(result.is_err());
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("string")
                || error_str.contains("length")
                || error_str.contains("limit"),
            "Expected string length limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_max_anchor_limit() {
    // Create a YAML with too many anchors
    let mut yaml_str = String::new();
    for i in 0..150 {
        yaml_str.push_str(&format!("item{}: &anchor{} value{}\n", i, i, i));
    }

    // Test with strict limits (max anchors = 100)
    let config = YamlConfig {
        limits: Limits::strict(),
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&yaml_str);

    assert!(result.is_err());
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("anchor") || error_str.contains("limit"),
            "Expected anchor limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_anchor_name_length_limit() {
    // A single anchor whose name exceeds max_string_length must be rejected
    // before it is materialized as a heap-allocated String / HashMap key.
    // Without a cap an attacker exhausts memory with one giant anchor name,
    // long before the per-anchor *count* limit could ever fire (issue #24).
    let huge_name = "a".repeat(70_000); // 70KB name (above strict 64KB limit)
    let yaml_str = format!("key: &{} value", huge_name);

    let config = YamlConfig {
        limits: Limits::strict(),
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&yaml_str);

    assert!(
        result.is_err(),
        "Expected an oversized anchor name to be rejected"
    );
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("string")
                || error_str.contains("length")
                || error_str.contains("limit"),
            "Expected string-length limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_alias_name_length_limit() {
    // The same unbounded-allocation hole exists for alias names (*name), which
    // share scan_identifier with anchors. Cap both (issue #24).
    let huge_name = "a".repeat(70_000);
    let yaml_str = format!("ref: *{}", huge_name);

    let config = YamlConfig {
        limits: Limits::strict(),
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&yaml_str);

    assert!(
        result.is_err(),
        "Expected an oversized alias name to be rejected"
    );
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("string")
                || error_str.contains("length")
                || error_str.contains("limit")
                || error_str.contains("alias"),
            "Expected string-length limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_max_document_size_limit() {
    // Create a document that exceeds size limit
    let large_doc = "x: ".to_string() + &"y".repeat(2_000_000); // 2MB document

    // Test with strict limits (max document size = 1MB)
    let config = YamlConfig {
        limits: Limits::strict(),
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&large_doc);

    assert!(result.is_err());
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("document")
                || error_str.contains("size")
                || error_str.contains("limit"),
            "Expected document size limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_max_collection_size_limit() {
    // Create a YAML with a collection that exceeds the strict limit
    // Using a smaller size to avoid timeout issues
    let mut yaml_str = String::new();
    for i in 0..200 {
        // Using 200 items which is above the test limit we'll set
        yaml_str.push_str(&format!("- item{}\n", i));
    }

    // Test with custom limits (set max collection size to 100)
    let mut limits = Limits::strict();
    limits.max_collection_size = 100; // Set limit to 100, test has 200 items

    let config = YamlConfig {
        limits,
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(&yaml_str);

    // This should fail either during parsing or construction
    if let Err(e) = result {
        let error_str = e.to_string();
        assert!(
            error_str.contains("collection")
                || error_str.contains("sequence")
                || error_str.contains("limit"),
            "Expected collection size limit error, got: {}",
            error_str
        );
    }
}

#[test]
fn test_secure_config() {
    // Test the secure configuration preset
    let config = YamlConfig::secure();
    let yaml = Yaml::with_config(config);

    // Should be able to parse normal documents
    let normal_yaml = "key: value\nlist:\n  - item1\n  - item2";
    let result = yaml.load_str(normal_yaml);
    assert!(result.is_ok());

    // But should reject suspicious patterns
    let suspicious_yaml = "x: ".to_string() + &"y".repeat(2_000_000); // 2MB string
    let result = yaml.load_str(&suspicious_yaml);
    assert!(result.is_err());
}

#[test]
fn test_billion_laughs_attack() {
    // Classic billion laughs attack (exponential expansion via aliases)
    let yaml_bomb = r#"
a: &a ["lol", "lol", "lol", "lol", "lol", "lol", "lol", "lol", "lol"]
b: &b [*a, *a, *a, *a, *a, *a, *a, *a, *a]
c: &c [*b, *b, *b, *b, *b, *b, *b, *b, *b]
d: &d [*c, *c, *c, *c, *c, *c, *c, *c, *c]
e: &e [*d, *d, *d, *d, *d, *d, *d, *d, *d]
f: &f [*e, *e, *e, *e, *e, *e, *e, *e, *e]
g: &g [*f, *f, *f, *f, *f, *f, *f, *f, *f]
"#;

    // This would expand to 9^7 = 4,782,969 "lol" strings without protection
    let config = YamlConfig {
        limits: Limits::strict(),
        loader_type: LoaderType::Safe,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(yaml_bomb);

    // Should fail with resource limit error, not consume excessive memory
    assert!(result.is_err(), "Should reject billion laughs attack");
    if let Err(e) = result {
        let error_msg = e.to_string();
        assert!(
            error_msg.contains("limit")
                || error_msg.contains("complexity")
                || error_msg.contains("alias")
                || error_msg.contains("collection"),
            "Should fail with resource limit error, got: {}",
            error_msg
        );
    }
}

#[test]
fn test_cyclic_alias_detection() {
    // Create cyclic reference - this is invalid YAML but shouldn't crash
    let yaml_str = r"
a: &a
  b: *b
b: &b
  a: *a
";

    let config = YamlConfig {
        limits: Limits::strict(),
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(yaml_str);

    // Should detect and reject cyclic references
    assert!(
        result.is_err(),
        "Should detect and reject cyclic references"
    );
}

#[test]
fn test_nested_alias_expansion_limit() {
    // Test nested alias expansion depth
    let yaml_str = r#"
a: &a "base"
b: &b [*a]
c: &c [*b]
d: &d [*c]
e: &e [*d]
f: &f [*e]
g: [*f]
"#;

    let config = YamlConfig {
        limits: Limits::strict(),
        ..YamlConfig::default()
    }; // max_alias_depth = 5

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(yaml_str);

    // Should fail when alias depth exceeds limit
    assert!(result.is_err(), "Should limit alias expansion depth");
}

#[test]
fn test_unlimited_config() {
    // Test that unlimited configuration allows large documents
    let config = YamlConfig {
        limits: Limits::unlimited(),
        ..YamlConfig::default()
    };
    let yaml = Yaml::with_config(config);

    // Should handle moderately large documents without issues
    let mut yaml_str = String::new();
    for i in 0..1000 {
        yaml_str.push_str(&format!("item{}: value{}\n", i, i));
    }

    let result = yaml.load_str(&yaml_str);
    assert!(result.is_ok());
}

#[test]
fn test_permissive_config() {
    // Test permissive configuration
    let config = YamlConfig {
        limits: Limits::permissive(),
        ..YamlConfig::default()
    };
    let yaml = Yaml::with_config(config);

    // Should handle large but reasonable documents
    let mut yaml_str = String::new();
    for i in 0..1000 {
        // Using 1000 items which should be fast enough in release mode
        yaml_str.push_str(&format!("- item{}\n", i));
    }

    let result = yaml.load_str(&yaml_str);
    // This may or may not succeed depending on implementation details
    // but should not panic
    let _ = result;
}

#[test]
fn test_cumulative_alias_materialization_cap() {
    // Regression for #15: cumulative alias node materialization must be
    // capped independently of max_complexity_score so wide fan-out cannot
    // allocate millions of nodes before any limit fires.
    //
    // *a has complexity 1 (seq) + 10 (len) + 10 = 21 nodes. With 20 sibling
    // expansions, the composer must materialize ~420 alias-expanded nodes.
    // A tight max_total_alias_nodes must reject this even when every other
    // limit is effectively unlimited.
    let yaml_str = r#"
a: &a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b: [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a]
"#;

    let config = YamlConfig {
        limits: permissive_with_alias_cap(100),
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str(yaml_str);

    assert!(
        result.is_err(),
        "expected cumulative alias materialization cap to reject the document"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("alias") || msg.contains("materializ") || msg.contains("limit"),
        "expected materialization-cap error message, got: {msg}"
    );
}

#[test]
fn test_cumulative_alias_materialization_cap_comment_preserving() {
    // Same regression for #15 via load_str_with_comments, which routes
    // through CommentPreservingComposer instead of BasicComposer. The
    // cap must apply uniformly across all public load paths.
    let yaml_str = r#"
a: &a [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
b: [*a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a, *a]
"#;

    let config = YamlConfig {
        limits: permissive_with_alias_cap(100),
        loader_type: LoaderType::RoundTrip,
        preserve_comments: true,
        ..YamlConfig::default()
    };

    let yaml = Yaml::with_config(config);
    let result = yaml.load_str_with_comments(yaml_str);

    assert!(
        result.is_err(),
        "expected materialization cap to fire through the comment-preserving path"
    );
    let msg = result.unwrap_err().to_string();
    assert!(
        msg.contains("alias") || msg.contains("materializ") || msg.contains("limit"),
        "expected materialization-cap error message, got: {msg}"
    );
}