uftp 0.1.0

UFTP 3.1, the USEF Flex Trading Protocol (LF Energy Shapeshifter), in Rust: all 26 messages, CS1 signing and a receive pipeline for DSOs and aggregators.
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
//! A bounded, DTD-free XML reader that builds a small element tree.
//!
//! The reader rejects the following:
//! - `<!DOCTYPE …>` and with it every entity declaration
//! - processing instructions other than the XML declaration
//! - documents that are not UTF-8
//! - non-whitespace text in UFTP elements (all UFTP data is in attributes)
//!
//! It enforces the byte, depth and element limits while it reads.
//!
//! Elements and attributes in an explicit, non-default namespace are extensions
//! `[UFTP §4.2]` and are skipped, though they still count against the limits. UFTP's own
//! elements are in no namespace (spec note SS-08).

use quick_xml::events::{BytesStart, Event};
use quick_xml::{Reader, XmlVersion};

use crate::error::{RejectKind, Rejection};

/// Bounds on what the decoder will read. Each can be lowered but never raised past a hard
/// cap, and none can be turned off.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Limits {
    max_bytes: usize,
    max_depth: usize,
    max_elements: usize,
}

impl Limits {
    /// The hard cap on document size: 64 MiB.
    pub const MAX_BYTES_CAP: usize = 64 * 1024 * 1024;
    /// The hard cap on element depth.
    pub const MAX_DEPTH_CAP: usize = 32;
    /// The hard cap on the number of elements.
    pub const MAX_ELEMENTS_CAP: usize = 4_000_000;

    /// Sets the byte limit, clamped to 1 byte through [`Self::MAX_BYTES_CAP`].
    #[must_use]
    pub fn with_max_bytes(mut self, n: usize) -> Self {
        self.max_bytes = n.clamp(1, Self::MAX_BYTES_CAP);
        self
    }

    /// Sets the depth limit, clamped to 1 through [`Self::MAX_DEPTH_CAP`].
    #[must_use]
    pub fn with_max_depth(mut self, n: usize) -> Self {
        self.max_depth = n.clamp(1, Self::MAX_DEPTH_CAP);
        self
    }

    /// Sets the element-count limit, clamped to 1 through [`Self::MAX_ELEMENTS_CAP`].
    #[must_use]
    pub fn with_max_elements(mut self, n: usize) -> Self {
        self.max_elements = n.clamp(1, Self::MAX_ELEMENTS_CAP);
        self
    }

    /// The byte limit. The same limit applies to the wrapper document and to the decoded
    /// body.
    #[must_use]
    pub fn max_bytes(&self) -> usize {
        self.max_bytes
    }

    /// The depth limit.
    #[must_use]
    pub fn max_depth(&self) -> usize {
        self.max_depth
    }

    /// The element-count limit.
    #[must_use]
    pub fn max_elements(&self) -> usize {
        self.max_elements
    }
}

impl Default for Limits {
    /// 4 MiB, depth 16, 250,000 elements: room for a monthly settlement of 30 orders ×
    /// 96 ISPs many times over. The deepest UFTP message is four levels deep.
    fn default() -> Self {
        Self {
            max_bytes: 4 * 1024 * 1024,
            max_depth: 16,
            max_elements: 250_000,
        }
    }
}

/// A UFTP element: its name, its un-namespaced attributes in document order, and its
/// UFTP child elements.
#[derive(Debug, Clone, PartialEq, Eq)]
pub(crate) struct Element {
    pub name: String,
    pub attrs: Vec<(String, String)>,
    pub children: Vec<Element>,
}

fn limits(message: String) -> Rejection {
    Rejection::new(RejectKind::Limits, "[decoder limits]", message)
}

fn malformed(e: impl std::fmt::Display) -> Rejection {
    Rejection::schema(
        "[UFTP §4.2] well-formed UTF-8 XML",
        format!("The document is not well-formed XML: {e}."),
    )
}

/// Namespace bindings in scope: (prefix, uri), with "" as the default namespace.
struct Scopes(Vec<Vec<(String, String)>>);

impl Scopes {
    fn lookup(&self, prefix: &str) -> Option<&str> {
        if prefix == "xml" {
            return Some("http://www.w3.org/XML/1998/namespace");
        }
        self.0
            .iter()
            .rev()
            .flat_map(|s| s.iter().rev())
            .find(|(p, _)| p == prefix)
            .map(|(_, u)| u.as_str())
    }
}

/// One element's name and attributes, read from a start tag.
struct Tag {
    name: String,
    namespaced: bool,
    attrs: Vec<(String, String)>,
    bindings: Vec<(String, String)>,
}

fn read_tag(start: &BytesStart<'_>, scopes: &Scopes) -> Result<Tag, Rejection> {
    let qname: String = start.name().as_ref().to_owned();
    let mut bindings = Vec::new();
    let mut raw = Vec::new();
    for attr in start.attributes() {
        let attr = attr.map_err(malformed)?;
        let key: String = attr.key.as_ref().to_owned();
        let value = attr
            .normalized_value(XmlVersion::Implicit1_0)
            .map_err(malformed)?
            .into_owned();
        if let Some(bad) = value.chars().find(|&c| !crate::xml::writer::is_xml_char(c)) {
            return Err(malformed(format!(
                "attribute {key} contains U+{:04X}, which XML does not allow",
                u32::from(bad),
                key = crate::error::quote(&key)
            )));
        }
        if key == "xmlns" {
            bindings.push((String::new(), value));
        } else if let Some(p) = key.strip_prefix("xmlns:") {
            if value.is_empty() {
                return Err(malformed(format!(
                    "namespace prefix {p} is bound to an empty name",
                    p = crate::error::quote(&p)
                )));
            }
            bindings.push((p.to_owned(), value));
        } else {
            raw.push((key, value));
        }
    }
    let with_own = |prefix: &str| -> Option<String> {
        bindings
            .iter()
            .rev()
            .find(|(p, _)| p == prefix)
            .map(|(_, u)| u.clone())
            .or_else(|| scopes.lookup(prefix).map(str::to_owned))
    };
    let (name, namespaced) = if let Some((prefix, local)) = qname.split_once(':') {
        if with_own(prefix).is_none() {
            return Err(malformed(format!(
                "prefix {prefix} of <{qname}> is not bound to a namespace",
                prefix = crate::error::quote(&prefix),
                qname = crate::error::name(&qname)
            )));
        }
        (local.to_owned(), true)
    } else {
        (qname.clone(), with_own("").is_some_and(|u| !u.is_empty()))
    };
    let mut attrs = Vec::new();
    for (key, value) in raw {
        match key.split_once(':') {
            // A prefixed attribute is an extension; unprefixed attributes are in no namespace.
            Some((prefix, _)) => {
                if with_own(prefix).is_none() {
                    return Err(malformed(format!(
                        "prefix {prefix} of attribute {key} is not bound to a namespace",
                        prefix = crate::error::quote(&prefix),
                        key = crate::error::quote(&key)
                    )));
                }
            }
            None => attrs.push((key, value)),
        }
    }
    Ok(Tag {
        name,
        namespaced,
        attrs,
        bindings,
    })
}

/// Parses `bytes` into the root UFTP element, enforcing `limits` while reading.
#[allow(clippy::too_many_lines)] // one event loop; splitting it would scatter the limit checks
pub(crate) fn parse(bytes: &[u8], limits: &Limits) -> Result<Element, Rejection> {
    if bytes.len() > limits.max_bytes {
        return Err(self::limits(format!(
            "The document has {} bytes; the limit is {}.",
            bytes.len(),
            limits.max_bytes
        )));
    }
    let text = std::str::from_utf8(bytes).map_err(|e| {
        Rejection::schema(
            "[UFTP §4.2] messages use UTF-8",
            format!(
                "The document is not UTF-8 (invalid byte at offset {}).",
                e.valid_up_to()
            ),
        )
    })?;
    let mut reader = Reader::from_str(text);
    let config = reader.config_mut();
    config.check_end_names = true;
    config.expand_empty_elements = false;

    let mut scopes = Scopes(Vec::new());
    // Open UFTP elements; `None` marks an extension subtree being skipped.
    let mut stack: Vec<Option<Element>> = Vec::new();
    let mut root: Option<Element> = None;
    let mut elements = 0usize;
    let mut seen_decl = false;
    let mut seen_any = false;

    loop {
        let event = reader.read_event().map_err(malformed)?;
        match event {
            Event::Decl(decl) => {
                if seen_decl || seen_any {
                    return Err(malformed("the XML declaration is not at the start"));
                }
                seen_decl = true;
                if let Some(enc) = decl.encoding() {
                    let enc = enc.map_err(malformed)?;
                    if !enc.eq_ignore_ascii_case("utf-8") {
                        return Err(Rejection::schema(
                            "[UFTP §4.2] messages use UTF-8",
                            format!(
                                "The document declares encoding {enc}.",
                                enc = crate::error::quote(&enc)
                            ),
                        ));
                    }
                }
            }
            Event::DocType(_) => {
                return Err(Rejection::schema(
                    "[XML] no DOCTYPE or entity declarations",
                    "The document contains a DOCTYPE; UFTP messages never do, and entity declarations are refused.",
                ));
            }
            Event::PI(_) => {
                return Err(Rejection::schema(
                    "[XML] no processing instructions",
                    "The document contains a processing instruction; only the XML declaration is allowed.",
                ));
            }
            Event::Start(ref start) | Event::Empty(ref start) => {
                seen_any = true;
                if root.is_some() && stack.is_empty() {
                    return Err(malformed("there is more than one root element"));
                }
                elements += 1;
                if elements > limits.max_elements {
                    return Err(self::limits(format!(
                        "The document has more than {} elements.",
                        limits.max_elements
                    )));
                }
                if stack.len() + 1 > limits.max_depth {
                    return Err(self::limits(format!(
                        "The document is nested deeper than {} levels.",
                        limits.max_depth
                    )));
                }
                let empty = matches!(event, Event::Empty(_));
                let tag = read_tag(start, &scopes)?;
                let in_extension = stack.iter().any(Option::is_none);
                let node = if in_extension || tag.namespaced {
                    if stack.is_empty() {
                        return Err(Rejection::schema(
                            "[XSD] UFTP messages are in no namespace (SS-08)",
                            format!(
                                "The root element <{}> is in a namespace; UFTP elements are not.",
                                crate::error::name(&tag.name)
                            ),
                        ));
                    }
                    None
                } else {
                    Some(Element {
                        name: tag.name,
                        attrs: tag.attrs,
                        children: Vec::new(),
                    })
                };
                if empty {
                    close(&mut stack, &mut root, node);
                } else {
                    scopes.0.push(tag.bindings);
                    stack.push(node);
                }
            }
            Event::End(_) => {
                scopes.0.pop();
                let node = stack
                    .pop()
                    .ok_or_else(|| malformed("an end tag has no start"))?;
                close(&mut stack, &mut root, node);
            }
            Event::Text(t) => {
                let in_uftp = stack.last().is_some_and(Option::is_some);
                let blank = t.as_ref().bytes().all(|b| b.is_ascii_whitespace());
                if !blank && (in_uftp || stack.is_empty()) {
                    return Err(Rejection::schema(
                        "[XSD] UFTP elements have no text content",
                        "The document has text where UFTP allows none.",
                    ));
                }
            }
            Event::GeneralRef(_) | Event::CData(_) => {
                let in_uftp = stack.last().is_some_and(Option::is_some);
                if in_uftp || stack.is_empty() {
                    return Err(Rejection::schema(
                        "[XSD] UFTP elements have no text content",
                        "The document has text where UFTP allows none.",
                    ));
                }
            }
            Event::Comment(_) => {}
            Event::Eof => break,
        }
    }
    if !stack.is_empty() {
        return Err(malformed("the document ends inside an element"));
    }
    root.ok_or_else(|| malformed("the document has no root element"))
}

fn close(stack: &mut [Option<Element>], root: &mut Option<Element>, node: Option<Element>) {
    match stack.last_mut() {
        Some(Some(parent)) => {
            if let Some(child) = node {
                parent.children.push(child);
            }
        }
        Some(None) => {}
        None => *root = node,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn p(s: &str) -> Result<Element, Rejection> {
        parse(s.as_bytes(), &Limits::default())
    }

    #[test]
    fn plain_tree() {
        let e =
            p(r#"<?xml version="1.0" encoding="UTF-8"?><A x="1"><B y="&lt;2"/><B/></A>"#).unwrap();
        assert_eq!(e.name, "A");
        assert_eq!(e.attrs, vec![("x".into(), "1".into())]);
        assert_eq!(e.children.len(), 2);
        assert_eq!(e.children[0].attrs[0].1, "<2");
    }

    #[test]
    fn doctype_refused() {
        let r = p(r#"<!DOCTYPE A [<!ENTITY x "y">]><A/>"#).unwrap_err();
        assert_eq!(r.rule_ref(), "[XML] no DOCTYPE or entity declarations");
    }

    #[test]
    fn undeclared_entity_refused() {
        assert!(p(r#"<A x="&x;"/>"#).is_err());
    }

    #[test]
    fn extension_elements_skipped() {
        let e = p(r#"<A xmlns:e="urn:ext"><e:X><Y/></e:X><B/><Z xmlns="urn:other"/></A>"#).unwrap();
        assert_eq!(e.children.len(), 1);
        assert_eq!(e.children[0].name, "B");
    }

    #[test]
    fn namespaced_root_refused() {
        assert!(p(r#"<A xmlns="urn:x"/>"#).is_err());
    }

    #[test]
    fn depth_and_count_limits() {
        let deep = format!("{}{}", "<A>".repeat(40), "</A>".repeat(40));
        assert_eq!(p(&deep).unwrap_err().kind(), RejectKind::Limits);
        let many = format!("<A>{}</A>", "<B/>".repeat(20));
        let r = parse(many.as_bytes(), &Limits::default().with_max_elements(10)).unwrap_err();
        assert_eq!(r.kind(), RejectKind::Limits);
    }

    #[test]
    fn forbidden_characters_refused() {
        // Raw or as a character reference.
        assert!(p("<A x=\"&#0;\"/>").is_err());
        assert!(p("<A x=\"&#x1B;\"/>").is_err());
        assert!(p("<A x=\"a\u{1}b\"/>").is_err());
        assert!(p("<A x=\"&#xFFFE;\"/>").is_err());
        assert_eq!(
            p("<A x=\"&#x9;\u{10348}\"/>").unwrap().attrs[0].1,
            "\t\u{10348}"
        );
    }

    #[test]
    fn text_refused() {
        assert!(p("<A>hello</A>").is_err());
        assert!(p("<A>\n  <B/>\n</A>").is_ok());
    }
}