kobold-json 0.1.0

Forensic JSON evidence packets for COBOL record migration: raw-byte custody, copybook/record hashes, field findings, round-trip proof. Clean-room; independent of GnuCOBOL/libcob.
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
//! `KOBOLD.JSON.PARSE.1` (FAIL-CLOSED) -- reconstruct the original record bytes from a packet + copybook.
//!
//! Two paths:
//!
//! * If the packet carries `raw_hex` for its leaf fields (an `Audit`/`Evidence` packet), reconstruct **the
//!   exact bytes** from the hex (`KOBOLD.JSON.ROUNDTRIP.1`: bytes -> packet -> bytes are identical).
//! * If the packet is value-only (`Compact`), **re-encode** each declared field's value into its PIC bytes,
//!   **failing closed** on overflow or an invalid value -- a value too long for an alphanumeric field, or a
//!   non-numeric value into a numeric field, yields a [`Finding`], never a silent truncation/coercion.
//!
//! On any failure the whole reconstruction fails closed: it returns `Err(findings)`, not partial bytes.
//! It is independent of GnuCOBOL/libcob.

use crate::json::JsonValue;
use crate::model::{Copybook, FieldDecl, FieldKind, Finding};

/// `KOBOLD.JSON.PARSE.1` -- reconstruct the record bytes declared by `copybook` from `packet`.
///
/// Returns `Ok(bytes)` exactly `copybook.record_length()` long, or `Err(findings)` listing every problem.
pub fn parse_into(copybook: &Copybook, packet: &JsonValue) -> Result<Vec<u8>, Vec<Finding>> {
    let fields = match packet.get("fields") {
        Some(f) => f,
        None => {
            return Err(vec![Finding::new(
                "PACKET_NO_FIELDS",
                "packet has no \"fields\" member".to_string(),
            )]);
        }
    };

    let total = copybook.record_length();
    let mut out = vec![b' '; total];
    let mut findings = Vec::new();

    encode_fields(&copybook.fields, fields, &mut out, &mut findings);

    if findings.is_empty() {
        Ok(out)
    } else {
        Err(findings)
    }
}

/// Encode a list of declarations into `out` (absolute offsets), reading each field's member from `node`.
fn encode_fields(decls: &[FieldDecl], node: &JsonValue, out: &mut [u8], findings: &mut Vec<Finding>) {
    for d in decls {
        let member = match node.get(&d.name) {
            Some(m) => m,
            None => {
                findings.push(Finding::new(
                    "FIELD_MISSING",
                    format!("field {} not present in packet", d.name),
                ));
                continue;
            }
        };
        encode_field(d, member, out, findings);
    }
}

/// Encode a single field. If the member is an Audit/Evidence detail object with `raw_hex`, use it (exact
/// reconstruction). If it carries nested `fields` (a group detail object), recurse. Otherwise treat the
/// member as a value and re-encode per the PIC.
fn encode_field(d: &FieldDecl, member: &JsonValue, out: &mut [u8], findings: &mut Vec<Finding>) {
    // Group declaration: recurse into nested fields, whether compact (object of values) or audit detail.
    if let FieldKind::Group(children) = &d.kind {
        let inner = member.get("fields").unwrap_or(member);
        encode_fields(children, inner, out, findings);
        return;
    }

    // Leaf. Prefer raw_hex when present (exact byte custody).
    if let Some(raw_hex) = member.get("raw_hex").and_then(|v| v.as_str()) {
        match decode_hex(raw_hex) {
            Ok(bytes) => {
                if bytes.len() != d.length {
                    findings.push(Finding::new(
                        "RAW_HEX_LENGTH",
                        format!(
                            "field {}: raw_hex decodes to {} bytes, declared length {}",
                            d.name,
                            bytes.len(),
                            d.length
                        ),
                    ));
                    return;
                }
                place(out, d.offset, &bytes, findings, &d.name);
                return;
            }
            Err(msg) => {
                findings.push(Finding::new("RAW_HEX_INVALID", format!("field {}: {}", d.name, msg)));
                return;
            }
        }
    }

    // Value-only re-encode.
    let value_node = member.get("value").unwrap_or(member);
    let value = match value_node {
        JsonValue::String(s) => s.clone(),
        JsonValue::Number(n) => n.clone(),
        JsonValue::Null => String::new(),
        _ => {
            findings.push(Finding::new(
                "VALUE_TYPE",
                format!("field {}: value is not a string/number", d.name),
            ));
            return;
        }
    };

    match &d.kind {
        FieldKind::Alphanumeric => encode_alnum(d, &value, out, findings),
        FieldKind::Numeric { scale, signed } => encode_numeric(d, &value, *scale, *signed, out, findings),
        FieldKind::Group(_) => unreachable!("group handled above"),
    }
}

/// Place `bytes` at absolute `offset` in `out`, failing closed if it would not fit.
fn place(out: &mut [u8], offset: usize, bytes: &[u8], findings: &mut Vec<Finding>, name: &str) {
    let end = offset + bytes.len();
    if end > out.len() {
        findings.push(Finding::new(
            "FIELD_OUT_OF_RANGE",
            format!("field {}: writing [{}..{}] exceeds record length {}", name, offset, end, out.len()),
        ));
        return;
    }
    out[offset..end].copy_from_slice(bytes);
}

/// Encode an alphanumeric value: pad with trailing spaces to the field length; **fail closed** if the value
/// is longer than the field (NO silent truncation).
fn encode_alnum(d: &FieldDecl, value: &str, out: &mut [u8], findings: &mut Vec<Finding>) {
    // 1:1 char->byte mapping (the inverse of export's render_alnum). Reject any char > 0xff.
    let mut bytes = Vec::with_capacity(value.len());
    for ch in value.chars() {
        let cp = ch as u32;
        if cp > 0xff {
            findings.push(Finding::new(
                "ALNUM_NON_BYTE",
                format!("field {}: char U+{:04X} is not representable in one byte", d.name, cp),
            ));
            return;
        }
        bytes.push(cp as u8);
    }
    if bytes.len() > d.length {
        findings.push(Finding::new(
            "VALUE_OVERFLOW",
            format!(
                "field {}: value of {} bytes overflows field length {} (fail-closed, no truncation)",
                d.name,
                bytes.len(),
                d.length
            ),
        ));
        return;
    }
    let mut buf = vec![b' '; d.length];
    buf[..bytes.len()].copy_from_slice(&bytes);
    place(out, d.offset, &buf, findings, &d.name);
}

/// Encode a numeric value into zoned-decimal display digits per the field's `scale`/`signed`. **Fails
/// closed** on a non-numeric value, too many integer digits for the field, or sign on an unsigned field.
fn encode_numeric(
    d: &FieldDecl,
    value: &str,
    scale: usize,
    signed: bool,
    out: &mut [u8],
    findings: &mut Vec<Finding>,
) {
    let mut s = value.trim();
    let mut negative = false;
    if let Some(rest) = s.strip_prefix('-') {
        negative = true;
        s = rest;
    } else if let Some(rest) = s.strip_prefix('+') {
        s = rest;
    }
    if negative && !signed {
        findings.push(Finding::new(
            "SIGN_ON_UNSIGNED",
            format!("field {}: negative value into unsigned PIC {}", d.name, d.pic),
        ));
        return;
    }

    // Split integer/fraction on a single decimal point.
    let (int_str, frac_str) = match s.split_once('.') {
        Some((i, f)) => (i, f),
        None => (s, ""),
    };
    if int_str.is_empty() && frac_str.is_empty() {
        findings.push(Finding::new("NUMERIC_EMPTY", format!("field {}: empty numeric value", d.name)));
        return;
    }
    for (label, part) in [("integer", int_str), ("fraction", frac_str)] {
        if !part.chars().all(|c| c.is_ascii_digit()) {
            findings.push(Finding::new(
                "NUMERIC_INVALID",
                format!("field {}: non-numeric {} part {:?} (fail-closed)", d.name, label, part),
            ));
            return;
        }
    }
    if frac_str.len() > scale {
        findings.push(Finding::new(
            "FRACTION_OVERFLOW",
            format!(
                "field {}: {} fraction digits exceed scale {} (fail-closed, no rounding)",
                d.name,
                frac_str.len(),
                scale
            ),
        ));
        return;
    }

    // Build the full digit string of length d.length: integer-part (left zero padded) + fraction (right
    // zero padded to scale).
    let int_digits = d.length.saturating_sub(scale);
    let int_trimmed = int_str.trim_start_matches('0');
    if int_trimmed.len() > int_digits {
        findings.push(Finding::new(
            "VALUE_OVERFLOW",
            format!(
                "field {}: integer part {:?} needs {} digits, field has {} (fail-closed)",
                d.name,
                int_str,
                int_trimmed.len(),
                int_digits
            ),
        ));
        return;
    }

    let mut digits = String::with_capacity(d.length);
    for _ in 0..(int_digits - int_trimmed.len()) {
        digits.push('0');
    }
    digits.push_str(int_trimmed);
    digits.push_str(frac_str);
    for _ in 0..(scale - frac_str.len()) {
        digits.push('0');
    }

    let mut bytes: Vec<u8> = digits.into_bytes();
    debug_assert_eq!(bytes.len(), d.length);
    if bytes.len() != d.length {
        findings.push(Finding::new(
            "NUMERIC_LENGTH",
            format!("field {}: built {} digits, declared length {}", d.name, bytes.len(), d.length),
        ));
        return;
    }

    // Apply the zoned sign overpunch to the last byte for a signed field.
    if signed {
        if let Some(last) = bytes.last_mut() {
            *last = overpunch_byte(*last, negative);
        }
    }
    place(out, d.offset, &bytes, findings, &d.name);
}

/// Map an ASCII digit byte + sign to its zoned overpunch byte (matches export's `overpunch`).
fn overpunch_byte(digit: u8, negative: bool) -> u8 {
    let n = digit.wrapping_sub(b'0');
    if n > 9 {
        return digit;
    }
    match (negative, n) {
        (false, 0) => b'{',
        (false, k) => b'A' + (k - 1),
        (true, 0) => b'}',
        (true, k) => b'J' + (k - 1),
    }
}

/// Decode a lowercase/uppercase hex string into bytes, fail-closed on odd length / non-hex.
pub fn decode_hex(s: &str) -> Result<Vec<u8>, String> {
    let b = s.as_bytes();
    if b.len() % 2 != 0 {
        return Err(format!("odd-length hex string ({} chars)", b.len()));
    }
    let mut out = Vec::with_capacity(b.len() / 2);
    let mut i = 0;
    while i < b.len() {
        let hi = hex_val(b[i]).ok_or_else(|| format!("invalid hex char {:?}", b[i] as char))?;
        let lo = hex_val(b[i + 1]).ok_or_else(|| format!("invalid hex char {:?}", b[i + 1] as char))?;
        out.push((hi << 4) | lo);
        i += 2;
    }
    Ok(out)
}

fn hex_val(c: u8) -> Option<u8> {
    match c {
        b'0'..=b'9' => Some(c - b'0'),
        b'a'..=b'f' => Some(c - b'a' + 10),
        b'A'..=b'F' => Some(c - b'A' + 10),
        _ => None,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::export::{export, Mode};

    fn copybook() -> Copybook {
        Copybook {
            record_name: "CUST".into(),
            encoding: "ascii".into(),
            fields: vec![
                FieldDecl::alnum("NAME", "X(4)", 0, 4),
                FieldDecl::numeric("AMT", "S9(3)V99", 4, 5, 2, true),
            ],
        }
    }

    #[test]
    fn roundtrip_evidence_identical_bytes() {
        // KOBOLD.JSON.ROUNDTRIP.1: bytes -> Evidence packet -> parse_into -> identical bytes.
        let cb = copybook();
        // AMT = -12.50 zoned: digits "0125" + overpunch of '0' negative = '}' -> "0125}"
        let rec = b"JOHN0125}";
        let packet = export(&cb, rec, Mode::Evidence);
        let back = parse_into(&cb, &packet).expect("roundtrip should succeed");
        assert_eq!(&back, rec);
    }

    #[test]
    fn roundtrip_audit_identical_bytes() {
        let cb = copybook();
        let rec = b"JANE0007A"; // AMT "0007A": A = +1 overpunch -> +0.071? check via export/import identity
        let packet = export(&cb, rec, Mode::Audit);
        let back = parse_into(&cb, &packet).expect("roundtrip should succeed");
        assert_eq!(&back, rec);
    }

    #[test]
    fn compact_reencode_succeeds() {
        let cb = Copybook {
            record_name: "R".into(),
            encoding: "ascii".into(),
            fields: vec![
                FieldDecl::alnum("NAME", "X(4)", 0, 4),
                FieldDecl::numeric("AMT", "9(3)V99", 4, 5, 2, false),
            ],
        };
        // Compact packet from values.
        let packet = export(&cb, b"AL  01250", Mode::Compact);
        let back = parse_into(&cb, &packet).expect("compact re-encode");
        assert_eq!(&back, b"AL  01250");
    }

    #[test]
    fn fail_closed_overflow_alnum() {
        // A compact packet whose NAME value is too long for the field -> Finding, not truncation.
        let cb = Copybook {
            record_name: "R".into(),
            encoding: "ascii".into(),
            fields: vec![FieldDecl::alnum("NAME", "X(4)", 0, 4)],
        };
        let packet = JsonValue::Object(vec![
            ("record".into(), JsonValue::str("R")),
            (
                "fields".into(),
                JsonValue::Object(vec![("NAME".into(), JsonValue::str("TOOLONG"))]),
            ),
        ]);
        let res = parse_into(&cb, &packet);
        let findings = res.expect_err("must fail closed on overflow");
        assert_eq!(findings[0].code, "VALUE_OVERFLOW");
    }

    #[test]
    fn fail_closed_nonnumeric() {
        let cb = Copybook {
            record_name: "R".into(),
            encoding: "ascii".into(),
            fields: vec![FieldDecl::numeric("AMT", "9(3)", 0, 3, 0, false)],
        };
        let packet = JsonValue::Object(vec![
            ("record".into(), JsonValue::str("R")),
            (
                "fields".into(),
                JsonValue::Object(vec![("AMT".into(), JsonValue::str("12X"))]),
            ),
        ]);
        let findings = parse_into(&cb, &packet).expect_err("must fail closed on non-numeric");
        assert_eq!(findings[0].code, "NUMERIC_INVALID");
    }

    #[test]
    fn decode_hex_fail_closed() {
        assert!(decode_hex("abc").is_err()); // odd
        assert!(decode_hex("zz").is_err()); // non-hex
        assert_eq!(decode_hex("4a4f").unwrap(), b"JO");
    }
}