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
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
//! Hardened XML reader — mirrors `org.pmml.model.SAXUtil` security.
//!
//! This module is the **only** place that enforces PMML XML hardening. It
//! wraps `quick-xml` 0.37's pull parser and adds the limits that `SAXUtil`
//! applies in the Java reference runtime: DTD/external entities disabled,
//! file-size cap, and nesting-depth cap. All unmarshaling in [`mod@crate::xml::unmarshal`]
//! must go through [`PmmlReader`] or [`new_reader`] so a single audit covers
//! every entry point.
//!
//! # What belongs here
//!
//! - [`PmmlReader`] — stateful wrapper that tracks element depth and delegates
//! to `quick_xml::Reader` with `trim_text(true)` and `expand_empty_elements(true)`.
//! - [`new_reader`] — stateless helper that returns a pre-configured `quick_xml::Reader`
//! when the caller will track depth itself (e.g. `unmarshal`'s own loop).
//! - The two `const` limits `MAX_DEPTH = 512` and `MAX_FILE_BYTES = 100 MB`
//! and the DTD/XXE policy.
//!
//! Nothing PMML-semantic belongs here: field types, `DataDictionary` parsing and
//! model lowering live in [`mod@crate::xml::unmarshal`] and `pmml-ir`. Keeping the layer
//! minimal makes the security review tractable.
//!
//! # Why separate `reader` from `unmarshal`
//!
//! `unmarshal` is ~5.7 kLOC of `quick-xml` pull logic that maps `pmml.xsd` elements
//! to [`crate::xml::unmarshal::RawPmml`]. Mixing depth/file guards into each parse
//! function would be error-prone and hard to audit. By extracting the guard into
//! `PmmlReader::read_event` / `new_reader` the hot-path XML loop stays small and
//! every path — tree, regression, mining, or the unsupported-model fallback —
//! inherits the same limits without duplicating checks.
//!
//! # How it relates to neighboring modules
//!
//! ```text
//! bytes: &[u8] ──► reader::PmmlReader / new_reader ──► unmarshal::unmarshal ──► RawPmml ──► pmmlruntime::ir::lower ──► Ir
//! (this module) (sibling) (pmml-ir crate)
//! ```
//!
//! - `pmml-core` provides [`crate::base::PmmlError`] / [`crate::base::Result`] used for
//! the two rejected cases below.
//! - `pmml-ir` and `pmml-session` never touch `quick-xml` directly; they receive the
//! already-validated `RawPmml`.
//!
//! # Security invariants
//!
//! - `MAX_DEPTH = 512` — `PmmlReader::read_event` increments on `Event::Start` and
//! errors with [`crate::base::PmmlError::ValidationError`] when `depth > 512`. Matches
//! `SAXUtil` and the `pmml.xsd` depth budget. `Event::Empty` does not increase depth.
//! - `MAX_FILE_BYTES = 100 MB` (`100 * 1024 * 1024`) — both [`PmmlReader::from_bytes`]
//! and [`new_reader`] reject `bytes.len() > MAX_FILE_BYTES` before creating a parser.
//! - DTD / XXE — `quick-xml` 0.37 does **not** expand entities by default and this
//! module never enables it. `<!DOCTYPE … [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]>`
//! is not resolved; the entity text (`&xxe;`) is returned verbatim, so file content
//! is never leaked. No DTD handling is implemented, external entities are not fetched.
//! - `trim_text(true)` and `expand_empty_elements(true)` are set on every reader so
//! `unmarshal` sees normalized `Event::Text` / `Event::Empty` regardless of the
//! PMML producer's whitespace.
//!
//! # Performance
//!
//! Depth tracking is a single `usize` increment per `Start`/`End`. No allocation
//! occurs in the fast path beyond `quick-xml`'s internal buffer.
use cratePmmlError;
use crateResult;
use Event;
use Reader;
const MAX_DEPTH: usize = 512;
const MAX_FILE_BYTES: usize = 100 * 1024 * 1024; // 100 MB
/// Hardened PMML reader that enforces `SAXUtil` limits on top of `quick-xml`.
///
/// Wraps `quick_xml::Reader<&[u8]>` and tracks nesting depth. It is the
/// preferred entry point for PMML XML; [`new_reader`] is the lower-level
/// alternative when the caller manages depth itself.
///
/// # Security
///
/// - File cap `100 MB` checked in [`PmmlReader::from_bytes`] before parsing.
/// - Depth cap `512` enforced in [`PmmlReader::read_event`].
/// - DTD/external entities disabled — `quick-xml` 0.37 does not expand entities
/// and this type never opts in, so XXE payloads are blocked. See the
/// module docs and [`new_reader`] for details.
///
/// # Examples
///
/// Basic construction and loop — mirrors how [`crate::xml::unmarshal::unmarshal`] uses it:
///
/// ```
/// use pmmlruntime::xml::PmmlReader;
/// use quick_xml::events::Event;
///
/// let xml = br#"<PMML version="4.4"><Header/><DataDictionary><DataField name="x" dataType="double" optype="continuous"/></DataDictionary></PMML>"#;
/// let mut r = PmmlReader::from_bytes(xml)?;
/// loop {
/// match r.read_event()? {
/// Event::Eof => break,
/// _ => {}
/// }
/// }
/// # Ok::<(), pmmlruntime::base::PmmlError>(())
/// ```
///
/// XXE payloads are not expanded (the `&xxe;` entity stays literal, file content is not leaked):
///
/// ```
/// use pmmlruntime::xml::PmmlReader;
/// use quick_xml::events::Event;
///
/// let xxe = br#"<?xml version="1.0"?><!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]><PMML version="4.4"><Header/></PMML>"#;
/// let mut r = PmmlReader::from_bytes(xxe)?;
/// let mut leaked = false;
/// loop {
/// match r.read_event()? {
/// Event::Text(t) if t.unescape().unwrap_or_default().contains("root:") => leaked = true,
/// Event::Eof => break,
/// _ => {}
/// }
/// }
/// assert!(!leaked);
/// # Ok::<(), pmmlruntime::base::PmmlError>(())
/// ```
/// Create a pre-configured `quick_xml::Reader` for PMML bytes.
///
/// Thin wrapper around `quick_xml::Reader::from_reader` that enforces the
/// same `100 MB` file cap and `trim_text`/`expand_empty_elements` settings as
/// [`PmmlReader::from_bytes`], but does **not** track depth. Use it when the
/// caller will drive `read_event_into` and depth itself (as `unmarshal` does
/// for its fine-grained `Loop { read_event_into }` patterns).
///
/// DTD/external entities remain disabled: `quick-xml` 0.37 does not expand
/// entities by default and this function does not enable it, so XXE payloads
/// are not resolved.
///
/// # Parameters
///
/// - `bytes`: complete PMML document.
///
/// # Return
///
/// `Ok(Reader)` on success, ready for `read_event_into(&mut buf)`.
///
/// # Errors
///
/// - [`crate::base::PmmlError::ValidationError`] if `bytes.len() > 100 MB`.
/// - No parse error here; malformed XML surfaces on the first `read_event_into` call.
///
/// # Panics
///
/// Never panics.
///
/// # Examples
///
/// ```
/// use pmmlruntime::xml::new_reader;
/// use quick_xml::events::Event;
///
/// let xml = br#"<PMML version="4.4"><Header/></PMML>"#;
/// let mut r = new_reader(xml)?;
/// let mut buf = Vec::new();
/// let ev = r.read_event_into(&mut buf)?;
/// // first event is Start(PMML) or Decl — not Eof
/// assert!(!matches!(ev, Event::Eof));
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
///
/// XXE is blocked — the entity text is not expanded to file content:
///
/// ```
/// use pmmlruntime::xml::new_reader;
/// use quick_xml::events::Event;
///
/// let xxe = br#"<?xml version="1.0"?><!DOCTYPE foo [ <!ENTITY xxe SYSTEM "file:///etc/passwd"> ]><PMML version="4.4"><Header/></PMML>"#;
/// let mut r = new_reader(xxe)?;
/// let mut buf = Vec::new();
/// let mut leaked = false;
/// loop {
/// match r.read_event_into(&mut buf) {
/// Ok(Event::Text(t)) if t.unescape().unwrap_or_default().contains("root:") => leaked = true,
/// Ok(Event::Eof) => break,
/// Ok(_) => {},
/// Err(_) => break,
/// }
/// buf.clear();
/// }
/// assert!(!leaked);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```