rubo4e 0.9.0

Rust implementation of the BO4E energy-market data standard
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
//! Parse-limit counters, [`JsonParseLimits`], and low-level helpers
//! for the hardened deserialization entry points.

use std::sync::atomic::{AtomicU64, Ordering};
#[cfg(feature = "tracing")]
use std::time::Instant;

use serde::de::DeserializeOwned;
use serde::de::Error as _;
// depth is a sibling module. depth imports only `trace_limit_violation` from limits,
// and limits imports only `DepthLimitedDeserializer`/`DepthState` from depth —
// no true circular data dependency exists, Rust handles this fine within a module tree.
use super::depth::{DepthLimitedDeserializer, DepthState};

#[cfg(feature = "simd-json")]
// Threshold below which serde_json is used even when `simd-json` is enabled.
// simd-json's parser setup cost exceeds its throughput advantage on small
// payloads; 2 KiB was empirically chosen on a 2024 ARM workstation
// (see `benches/json_perf.rs`). Adjust if your payload distribution differs.
const SIMD_JSON_STR_MIN_BYTES: usize = 2048;

// For mutable-byte APIs, simd-json can still lose on small/medium payloads due
// to parser setup costs. Prefer serde_json below this threshold.
// 1.5 KiB is slightly lower than the str threshold because the byte path avoids
// the UTF-8 validation copy that the str path pays.
#[cfg(feature = "simd-json")]
const SIMD_JSON_BYTES_MIN_BYTES: usize = 1536;

#[inline]
pub(super) fn trace_deser_error<T>(result: &Result<T, serde_json::Error>, context: &'static str) {
    #[cfg(feature = "tracing")]
    if let Err(ref e) = result {
        tracing::debug!(error = %e, "{context}");
    }
    #[cfg(not(feature = "tracing"))]
    {
        let _ = (result, context);
    }
}

#[cfg(feature = "tracing")]
pub(super) fn trace_json_outcome(
    operation: &'static str,
    mode: &'static str,
    bo_type: &'static str,
    input_len: Option<usize>,
    output_len: Option<usize>,
    start: Instant,
    ok: bool,
) {
    let elapsed_us = start.elapsed().as_micros() as u64;
    tracing::debug!(
        operation,
        mode,
        bo_type,
        input_len,
        output_len,
        ok,
        elapsed_us,
        "bo4e json operation completed"
    );
}

/// The resource limits this crate enforces while parsing JSON.
///
/// A closed enum rather than a string tag: it makes the counter dispatch below
/// exhaustive, so adding a limit cannot silently miss its counter.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(super) enum LimitKind {
    PayloadBytes,
    NestingDepth,
    ExtensionValueBytes,
    ExtensionFieldCount,
    ExtensionKeyLen,
}

impl LimitKind {
    /// Stable label used for `tracing` fields and the `metrics` counter tag.
    #[cfg(any(feature = "tracing", feature = "metrics"))]
    const fn as_str(self) -> &'static str {
        match self {
            Self::PayloadBytes => "payload_bytes",
            Self::NestingDepth => "nesting_depth",
            Self::ExtensionValueBytes => "extension_value_bytes",
            Self::ExtensionFieldCount => "extension_field_count",
            Self::ExtensionKeyLen => "extension_key_len",
        }
    }

    fn counter(self) -> &'static AtomicU64 {
        match self {
            Self::PayloadBytes => &JSON_LIMIT_HIT_PAYLOAD_BYTES,
            Self::NestingDepth => &JSON_LIMIT_HIT_NESTING_DEPTH,
            Self::ExtensionValueBytes => &JSON_LIMIT_HIT_EXTENSION_VALUE_BYTES,
            Self::ExtensionFieldCount => &JSON_LIMIT_HIT_EXTENSION_FIELD_COUNT,
            Self::ExtensionKeyLen => &JSON_LIMIT_HIT_EXTENSION_KEY_LEN,
        }
    }
}

pub(super) fn trace_limit_violation(kind: LimitKind, actual: usize, limit: usize) {
    kind.counter().fetch_add(1, Ordering::Relaxed);

    #[cfg(feature = "metrics")]
    metrics::counter!("bo4e_json_limit_hit_total", "kind" => kind.as_str()).increment(1);

    #[cfg(feature = "tracing")]
    tracing::warn!(
        kind = kind.as_str(),
        actual,
        limit,
        "bo4e json parse limit exceeded"
    );
    #[cfg(not(any(feature = "tracing", feature = "metrics")))]
    let _ = (actual, limit);
}

static JSON_LIMIT_HIT_PAYLOAD_BYTES: AtomicU64 = AtomicU64::new(0);
static JSON_LIMIT_HIT_NESTING_DEPTH: AtomicU64 = AtomicU64::new(0);
static JSON_LIMIT_HIT_EXTENSION_VALUE_BYTES: AtomicU64 = AtomicU64::new(0);
static JSON_LIMIT_HIT_EXTENSION_FIELD_COUNT: AtomicU64 = AtomicU64::new(0);
static JSON_LIMIT_HIT_EXTENSION_KEY_LEN: AtomicU64 = AtomicU64::new(0);

/// Snapshot of JSON hardening limit-hit counters.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct JsonLimitHitCounters {
    /// Number of payload-size limit violations.
    pub payload_bytes: u64,
    /// Number of nesting-depth limit violations.
    pub nesting_depth: u64,
    /// Number of extension-value-budget limit violations.
    pub extension_value_bytes: u64,
    /// Number of extension-field-count limit violations.
    pub extension_field_count: u64,
    /// Number of extension-field-key-length limit violations.
    pub extension_key_len: u64,
}

/// Returns a snapshot of JSON hardening limit-hit counters for this process.
#[must_use]
pub fn json_limit_hit_counters() -> JsonLimitHitCounters {
    JsonLimitHitCounters {
        payload_bytes: JSON_LIMIT_HIT_PAYLOAD_BYTES.load(Ordering::Relaxed),
        nesting_depth: JSON_LIMIT_HIT_NESTING_DEPTH.load(Ordering::Relaxed),
        extension_value_bytes: JSON_LIMIT_HIT_EXTENSION_VALUE_BYTES.load(Ordering::Relaxed),
        extension_field_count: JSON_LIMIT_HIT_EXTENSION_FIELD_COUNT.load(Ordering::Relaxed),
        extension_key_len: JSON_LIMIT_HIT_EXTENSION_KEY_LEN.load(Ordering::Relaxed),
    }
}

/// Optional hardening limits for JSON deserialization entry points.
///
/// Use with the `*_hardened` methods on `Bo4eJsonExt` to constrain resource
/// usage when parsing untrusted payloads.
#[derive(Debug, Clone, Copy, Default)]
pub struct JsonParseLimits {
    /// Maximum allowed input payload size in bytes.
    pub max_payload_bytes: Option<usize>,
    /// Maximum allowed JSON nesting depth.
    pub max_nesting_depth: Option<usize>,
    /// Maximum cumulative size budget for captured extension values.
    pub max_extension_value_bytes: Option<usize>,
    /// Maximum number of extension fields accepted per struct.
    ///
    /// This is a softer per-call limit that sits below the process-wide hard cap
    /// of [`crate::json::MAX_EXTENSION_FIELDS`], which is enforced during deserialization.
    /// Use this to apply a tighter bound for specific untrusted inputs.
    pub max_extension_field_count: Option<usize>,
}

impl JsonParseLimits {
    /// Returns a limit set with all caps disabled.
    #[must_use]
    pub const fn unlimited() -> Self {
        Self {
            max_payload_bytes: None,
            max_nesting_depth: None,
            max_extension_value_bytes: None,
            max_extension_field_count: None,
        }
    }

    /// Returns a conservative default profile for untrusted external inputs.
    #[must_use]
    pub const fn untrusted_defaults() -> Self {
        Self {
            max_payload_bytes: Some(1_000_000),
            max_nesting_depth: Some(64),
            max_extension_value_bytes: Some(64_000),
            max_extension_field_count: Some(32),
        }
    }
}

// ─── Parse-time extension budget ─────────────────────────────────────────────
//
// The extension caps must apply to *every* struct in the payload, not just the
// root.  A post-hoc check on the deserialized root can only ever see the root's
// own `_additional` map, so extension data hidden inside a nested COM (e.g.
// `marktlokation.lokationsadresse`) escapes it entirely.
//
// The budget is therefore installed for the duration of one hardened call and
// consulted by `LimitedExtensionMap::deserialize` at every nesting level.  That
// also makes enforcement fail-fast: an oversized payload is rejected while it is
// being parsed, instead of after the whole tree has been materialized.
//
// A thread-local is sound here because a single `from_json_*` call is entirely
// synchronous — it never yields, so no other task can observe or share the
// scope.  `BudgetGuard` saves and restores the previous value, so nested
// hardened calls compose correctly.

thread_local! {
    static EXTENSION_BUDGET: std::cell::Cell<Option<ExtensionBudget>> =
        const { std::cell::Cell::new(None) };
}

/// Remaining extension allowance for the hardened call currently in progress.
#[derive(Debug, Clone, Copy)]
pub(super) struct ExtensionBudget {
    /// Cumulative value-byte allowance left for the whole payload.
    remaining_bytes: Option<usize>,
    /// Per-struct field-count cap (not consumed; re-checked at each struct).
    max_fields_per_struct: Option<usize>,
}

/// RAII guard that installs an [`ExtensionBudget`] and restores the previous one.
pub(super) struct BudgetGuard(Option<ExtensionBudget>);

impl Drop for BudgetGuard {
    fn drop(&mut self) {
        EXTENSION_BUDGET.with(|b| b.set(self.0));
    }
}

/// Installs the extension budget described by `limits` for the current scope.
///
/// Returns `None` when `limits` constrains nothing, so the common path costs no
/// thread-local access during parsing.
pub(super) fn install_extension_budget(limits: JsonParseLimits) -> Option<BudgetGuard> {
    if limits.max_extension_value_bytes.is_none() && limits.max_extension_field_count.is_none() {
        return None;
    }
    let budget = ExtensionBudget {
        remaining_bytes: limits.max_extension_value_bytes,
        max_fields_per_struct: limits.max_extension_field_count,
    };
    let previous = EXTENSION_BUDGET.with(|b| b.replace(Some(budget)));
    Some(BudgetGuard(previous))
}

/// Returns the per-struct extension field-count cap, if a budget is installed.
#[inline]
pub(super) fn budget_max_fields_per_struct() -> Option<usize> {
    EXTENSION_BUDGET
        .with(|b| b.get())
        .and_then(|b| b.max_fields_per_struct)
}

/// Charges `bytes` against the cumulative value-byte allowance.
///
/// Returns `Err` with the exceeded limit once the allowance is exhausted. A
/// no-op when no budget is installed or no byte cap was configured.
#[inline]
pub(super) fn charge_extension_bytes(bytes: usize) -> Result<(), usize> {
    EXTENSION_BUDGET.with(|cell| {
        let Some(mut budget) = cell.get() else {
            return Ok(());
        };
        let Some(remaining) = budget.remaining_bytes else {
            return Ok(());
        };
        let Some(left) = remaining.checked_sub(bytes) else {
            return Err(bytes);
        };
        budget.remaining_bytes = Some(left);
        cell.set(Some(budget));
        Ok(())
    })
}

/// Default maximum JSON nesting depth for all non-hardened deserialization paths.
///
/// Valid BO4E structures are at most 6–8 levels deep in practice.  128 is a
/// generous allowance that eliminates the stack-overflow DoS surface while
/// accepting all legitimate payloads.
///
/// The `_hardened` variants accept an explicit [`JsonParseLimits::max_nesting_depth`]
/// which, when set, takes priority over this default.
pub(super) const DEFAULT_MAX_NESTING_DEPTH: usize = 128;

/// Scans `bytes` for the maximum JSON nesting depth without parsing.
///
/// Only reachable on the `simd-json` code path; the `serde_json` path enforces
/// depth inline via `DepthLimitedDeserializer` and never needs a pre-scan.
///
/// This is a single-pass linear scan that correctly skips `{` / `[` / `}` / `]`
/// characters inside JSON string values (honouring `\"` escape sequences).  It
/// does **not** do full JSON validation — it is only used to guard against
/// deeply-nested payloads before handing off to the real parser.
///
/// Used by [`deserialize_german_from_str`] / [`deserialize_german_from_slice`]
/// on code paths where `simd-json` is active, because the SIMD parser does not
/// support visitor wrapping and therefore cannot use `DepthLimitedDeserializer`.
/// The `_hardened` variants use the true single-pass visitor approach instead.
#[cfg(feature = "simd-json")]
pub(super) fn scan_max_nesting_depth(bytes: &[u8]) -> usize {
    let mut depth: usize = 0;
    let mut max: usize = 0;
    let mut in_string = false;
    let mut i = 0;
    while i < bytes.len() {
        let b = bytes[i];
        if in_string {
            if b == b'\\' {
                i += 1; // skip the next escaped byte (could be '"' or another escape)
            } else if b == b'"' {
                in_string = false;
            }
        } else {
            match b {
                b'"' => in_string = true,
                b'{' | b'[' => {
                    depth += 1;
                    if depth > max {
                        max = depth;
                    }
                }
                b'}' | b']' => {
                    depth = depth.saturating_sub(1);
                }
                _ => {}
            }
        }
        i += 1;
    }
    max
}

pub(super) fn check_payload_limit(
    payload_len: usize,
    limits: JsonParseLimits,
) -> Result<(), serde_json::Error> {
    if let Some(max) = limits.max_payload_bytes {
        if payload_len > max {
            trace_limit_violation(LimitKind::PayloadBytes, payload_len, max);
            return Err(serde_json::Error::custom(format!(
                "payload too large: {payload_len} bytes exceeds limit {max}"
            )));
        }
    }
    Ok(())
}

/// Checks `bytes` against [`DEFAULT_MAX_NESTING_DEPTH`] using a pre-scan.
///
/// Returns a serde error if the depth is exceeded.  Called on paths where
/// `DepthLimitedDeserializer` cannot be used (simd-json).
#[cfg(feature = "simd-json")]
pub(super) fn check_default_depth(bytes: &[u8]) -> Result<(), serde_json::Error> {
    let actual = scan_max_nesting_depth(bytes);
    if actual > DEFAULT_MAX_NESTING_DEPTH {
        trace_limit_violation(LimitKind::NestingDepth, actual, DEFAULT_MAX_NESTING_DEPTH);
        Err(serde_json::Error::custom(format!(
            "JSON nesting depth {actual} exceeds default limit {DEFAULT_MAX_NESTING_DEPTH}; \
             use from_json_german_hardened with a JsonParseLimits to adjust"
        )))
    } else {
        Ok(())
    }
}

pub(super) fn deserialize_german_from_str<T: DeserializeOwned>(
    s: &str,
) -> Result<T, serde_json::Error> {
    #[cfg(feature = "simd-json")]
    {
        if s.len() < SIMD_JSON_STR_MIN_BYTES {
            // Small payload: fall through to the serde_json single-pass path below.
        } else {
            // Large payload: simd-json does not support visitor wrapping, so we
            // pre-scan the raw bytes for nesting depth before dispatching.
            check_default_depth(s.as_bytes())?;
            let mut buf = s.as_bytes().to_vec();
            return simd_json::from_slice::<T>(&mut buf).map_err(serde_json::Error::custom);
        }
    }
    // serde_json path: single-pass depth enforcement via DepthLimitedDeserializer.
    let state = DepthState::new(DEFAULT_MAX_NESTING_DEPTH);
    let mut de = serde_json::Deserializer::from_str(s);
    T::deserialize(DepthLimitedDeserializer::new(&mut de, &state))
}

pub(super) fn deserialize_german_from_slice<T: DeserializeOwned>(
    bytes: &[u8],
) -> Result<T, serde_json::Error> {
    #[cfg(feature = "simd-json")]
    {
        if bytes.len() < SIMD_JSON_BYTES_MIN_BYTES {
            // Small payload: fall through to the serde_json single-pass path below.
        } else {
            // Large payload: pre-scan depth before simd-json (no visitor wrapping available).
            check_default_depth(bytes)?;
            let mut buf = bytes.to_vec();
            return simd_json::from_slice::<T>(&mut buf).map_err(serde_json::Error::custom);
        }
    }
    // serde_json path: single-pass depth enforcement via DepthLimitedDeserializer.
    let state = DepthState::new(DEFAULT_MAX_NESTING_DEPTH);
    let mut de = serde_json::Deserializer::from_slice(bytes);
    T::deserialize(DepthLimitedDeserializer::new(&mut de, &state))
}