enprot 0.4.1

Engyon Protected Text (EPT) — confidentiality processor and capability ledger
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
// Copyright (c) 2018-2026 [Ribose Inc](https://www.ribose.com).
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
// 1. Redistributions of source code must retain the above copyright
//    notice, this list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright
//    notice, this list of conditions and the following disclaimer in the
//    documentation and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
// ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

//! EPT markup parser. Line-oriented: a non-directive line folds into
//! the preceding `Plain` node; a directive line is dispatched to the
//! per-command parser by `Command::from_keyword`.

use std::collections::{BTreeMap, HashSet};
use std::io::BufRead;

use crate::error::{Error, Result};
use crate::etree::{Command, ParseOps, TextNode, TextTree, parse_error};
use crate::utils;

/// In-progress frame on the parser stack. The `text` accumulator is
/// always the "current target" — what new nodes get pushed onto. When
/// a frame opens, the outer text is saved into the frame and `text`
/// is cleared; when the frame closes, the saved outer text becomes
/// the new accumulator and the just-collected `text` becomes the
/// frame's children.
///
/// `Conflict` is the one variant that collects into *two* children
/// (`ours`, `theirs`); `mode` tracks which side `text` is currently
/// filling. OURS/THEIRS directives flip the mode and stash the
/// accumulated nodes into the appropriate field.
enum Frame {
    BeginEnd {
        keyw: String,
        outer: TextTree,
    },
    Encrypted {
        keyw: String,
        outer: TextTree,
        extfields: BTreeMap<String, String>,
    },
    Conflict {
        keyw: String,
        outer: TextTree,
        ours: TextTree,
        mode: ConflictMode,
    },
}

#[derive(Copy, Clone, Eq, PartialEq, Debug)]
enum ConflictMode {
    Ours,
    Theirs,
}

pub fn parse<R>(buf_in: R, paops: &mut ParseOps) -> Result<TextTree>
where
    R: BufRead,
{
    if paops.max_depth != 0 && paops.runtime.level > paops.max_depth {
        return Err(Error::Msg("Maximum recursion depth!".into()));
    }

    let mut text = Vec::new();
    let mut lineno = 0;
    let mut pstack: Vec<Frame> = Vec::new();

    for line_in in buf_in.lines() {
        let line = line_in?;
        lineno += 1;

        if !line.trim_start().starts_with(&paops.separators.left) {
            if let Some(TextNode::Plain(last)) = text.last_mut() {
                last.push('\n');
                last.push_str(&line);
                continue;
            }
            text.push(TextNode::Plain(line.clone()));
            continue;
        }

        // Directive parsing: avoid allocating a new String via
        // replacen. Work with slices from the original line.
        // (TODO.finalize/40 — parser perf.)
        let trimmed = line.trim();
        let after_left = trimmed
            .strip_prefix(&paops.separators.left)
            .unwrap_or(trimmed);
        let inner = match after_left.strip_suffix(&paops.separators.right) {
            Some(s) => s,
            None => {
                return Err(parse_error(
                    paops,
                    lineno,
                    &line,
                    format!("Right separator '{}' missing.", paops.separators.right),
                ));
            }
        };
        let mut parts = inner.split_whitespace();
        let kw = match parts.next() {
            Some(k) => k,
            None => continue,
        };

        let parsed = match Command::from_keyword(kw) {
            Some(c) => c,
            None => {
                return Err(parse_error(
                    paops,
                    lineno,
                    &line,
                    format!("Unknown section '{}'.", kw),
                ));
            }
        };

        let rest: Vec<&str> = parts.collect();
        match parsed {
            Command::Data => parse_data(&rest, &line, lineno, paops, &mut text)?,
            Command::Begin => parse_begin(&rest, &line, lineno, paops, &mut pstack, &mut text)?,
            Command::Encrypted => {
                parse_encrypted(&rest, &line, lineno, paops, &mut pstack, &mut text)?
            }
            Command::End => parse_end(&rest, &line, lineno, paops, &mut pstack, &mut text)?,
            Command::Stored => parse_stored(&rest, &line, lineno, paops, &mut text)?,
            Command::Chain => parse_chain(&rest, &line, lineno, paops, &mut text)?,
            Command::Include => parse_include(&rest, &line, lineno, paops, &mut text)?,
            Command::Conflict => {
                parse_conflict(&rest, &line, lineno, paops, &mut pstack, &mut text)?
            }
            Command::Ours => parse_ours(&line, lineno, paops, &mut pstack, &mut text)?,
            Command::Theirs => parse_theirs(&line, lineno, paops, &mut pstack, &mut text)?,
        }
    }

    if !pstack.is_empty() {
        for top in pstack.into_iter().rev() {
            match top {
                Frame::BeginEnd { keyw, .. } => {
                    eprintln!("Parse: BEGIN {} without END.", keyw);
                }
                Frame::Encrypted { keyw, .. } => {
                    eprintln!("Parse: ENCRYPTED {} without END.", keyw);
                }
                Frame::Conflict { keyw, .. } => {
                    eprintln!("Parse: CONFLICT {} without END.", keyw);
                }
            }
        }
        return Err(Error::Parse {
            file: paops.runtime.fname.clone(),
            lineno: 0,
            msg: "Unclosed section".into(),
        });
    }

    Ok(text)
}

fn parse_data(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &ParseOps,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    for tok in cmd {
        let mut data = match utils::base64_decode(tok) {
            Ok(d) => d,
            Err(e) => {
                return Err(parse_error(
                    paops,
                    lineno,
                    line,
                    format!("Error decoding base64 in '{}': {}", tok, e),
                ));
            }
        };
        if let Some(TextNode::Data(last)) = text.last_mut() {
            last.append(&mut data);
        } else {
            text.push(TextNode::Data(data));
        }
    }
    Ok(())
}

fn parse_begin(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &mut ParseOps,
    pstack: &mut Vec<Frame>,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    if cmd.len() != 1 {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "BEGIN needs a single keyword.",
        ));
    }
    paops.runtime.level += 1;
    pstack.push(Frame::BeginEnd {
        keyw: cmd[0].to_owned(),
        outer: std::mem::take(text),
    });
    Ok(())
}

pub(crate) fn parse_encrypted_extfields(
    cmd: &[&str],
    paops: &ParseOps,
    lineno: i32,
    line: &str,
) -> Result<BTreeMap<String, String>> {
    let mut extfields: BTreeMap<String, String> = BTreeMap::new();
    for field in cmd.iter().rev() {
        if field.find(':').is_none() {
            break;
        }
        let (key, value) = field.split_once(':').unwrap();

        if extfields.contains_key(key) {
            return Err(parse_error(
                paops,
                lineno,
                line,
                format!("Duplicate extended field '{}'", key),
            ));
        }
        extfields.insert(key.to_string(), value.to_string());
    }
    Ok(extfields)
}

fn parse_encrypted(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &mut ParseOps,
    pstack: &mut Vec<Frame>,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    let extfields = parse_encrypted_extfields(cmd, paops, lineno, line)?;
    let param_count = cmd.len() - extfields.len();
    let extfield_keys: HashSet<String> = extfields.keys().cloned().collect();
    let known_extfields: HashSet<String> = ["pbkdf".to_string(), "cipher".to_string()]
        .into_iter()
        .collect();
    if extfield_keys.difference(&known_extfields).next().is_some() {
        eprintln!("Warning: Unrecognized extended field(s) present");
    }

    match param_count {
        1 => {
            paops.runtime.level += 1;
            pstack.push(Frame::Encrypted {
                keyw: cmd[0].to_owned(),
                outer: std::mem::take(text),
                extfields,
            });
            Ok(())
        }
        2 => {
            if cmd[1].len() != 64 {
                return Err(parse_error(paops, lineno, line, "Invalid CAS identifier"));
            }
            let node = vec![TextNode::Stored {
                keyw: "ct".to_string(),
                cas: cmd[1].to_string(),
            }];
            text.push(TextNode::Encrypted {
                keyw: cmd[0].to_string(),
                txt: node,
                extfields,
            });
            Ok(())
        }
        _ => Err(parse_error(
            paops,
            lineno,
            line,
            format!(
                "ENCRYPTED has wrong number of parameters ({}).",
                param_count
            ),
        )),
    }
}

fn parse_end(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &mut ParseOps,
    pstack: &mut Vec<Frame>,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    if cmd.len() > 1 {
        return Err(parse_error(paops, lineno, line, "Unknown padding in END."));
    }

    match pstack.pop() {
        Some(Frame::BeginEnd { keyw, outer }) => {
            if !cmd.is_empty() && keyw != cmd[0] {
                return Err(parse_error(
                    paops,
                    lineno,
                    line,
                    format!("END mismatch (expected '{}').", keyw),
                ));
            }
            let node = TextNode::BeginEnd {
                keyw,
                txt: std::mem::take(text),
            };
            *text = outer;
            text.push(node);
            paops.runtime.level -= 1;
            Ok(())
        }
        Some(Frame::Encrypted {
            keyw,
            outer,
            extfields,
        }) => {
            if keyw != cmd[0] {
                return Err(parse_error(
                    paops,
                    lineno,
                    line,
                    format!("END mismatch (expected '{}').", keyw),
                ));
            }
            if text.len() != 1 {
                return Err(parse_error(
                    paops,
                    lineno,
                    line,
                    format!(
                        "{} elements in encrypted {} (must be a single DATA or STORED).",
                        text.len(),
                        keyw
                    ),
                ));
            }
            match text[0] {
                TextNode::Data(_) | TextNode::Stored { .. } => {
                    let node = TextNode::Encrypted {
                        keyw,
                        txt: std::mem::take(text),
                        extfields,
                    };
                    *text = outer;
                    text.push(node);
                    paops.runtime.level -= 1;
                    Ok(())
                }
                _ => Err(parse_error(
                    paops,
                    lineno,
                    line,
                    format!("Not DATA or STORED element in encrypted {}.", keyw),
                )),
            }
        }
        Some(Frame::Conflict {
            keyw,
            outer,
            ours,
            mode,
        }) => {
            if !cmd.is_empty() && keyw != cmd[0] {
                return Err(parse_error(
                    paops,
                    lineno,
                    line,
                    format!("END mismatch (expected '{}').", keyw),
                ));
            }
            // Whatever was in `text` belongs to the side currently
            // in `mode`. The other side was already stashed when the
            // mode-switch directive fired.
            let (ours, theirs) = match mode {
                ConflictMode::Ours => (std::mem::take(text), ours),
                ConflictMode::Theirs => (ours, std::mem::take(text)),
            };
            let node = TextNode::Conflict { keyw, ours, theirs };
            *text = outer;
            text.push(node);
            paops.runtime.level -= 1;
            Ok(())
        }
        None => Err(parse_error(
            paops,
            lineno,
            line,
            "END without a start clause.",
        )),
    }
}

fn parse_stored(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &ParseOps,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    if cmd.len() != 2 {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "STORED needs two parameters.",
        ));
    }
    text.push(TextNode::Stored {
        keyw: cmd[0].to_owned(),
        cas: cmd[1].to_owned(),
    });
    Ok(())
}

/// Parse a `CHAIN` directive line. All fields use the same
/// `key:value` extfield format as `ENCRYPTED`; the resulting map
/// becomes a [`TextNode::Chain`]. Required fields (`parents`,
/// `signer`, `payload`, `sig`) are validated by the verifier
/// (`verify-chain`, TODO.finalize/18), not here — the parser
/// accepts anything that parses as extfields so unknown-future
/// fields don't break old parsers.
fn parse_chain(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &ParseOps,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    let extfields = parse_encrypted_extfields(cmd, paops, lineno, line)?;
    if extfields.is_empty() {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "CHAIN needs at least one key:value field (parents / signer / payload / sig).",
        ));
    }
    text.push(TextNode::Chain { extfields });
    Ok(())
}

/// Parse an `INCLUDE <hash>` directive. The hash is a CAS blob ID
/// pointing to another EPT file. Resolution (loading the referenced
/// file, recursive verification) is NOT done by the parser — callers
/// like `verify-chain --include-path` handle it.
fn parse_include(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &ParseOps,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    if cmd.len() != 1 {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "INCLUDE needs exactly one hash parameter.",
        ));
    }
    text.push(TextNode::Include {
        hash: cmd[0].to_owned(),
    });
    Ok(())
}

/// Open a CONFLICT block. Like BEGIN, but the block holds two
/// labelled sub-trees (`ours`, `theirs`) instead of one. Mode starts
/// in `Ours`; the OURS directive flips the mode and stashes whatever
/// has been collected so far.
fn parse_conflict(
    cmd: &[&str],
    line: &str,
    lineno: i32,
    paops: &mut ParseOps,
    pstack: &mut Vec<Frame>,
    text: &mut Vec<TextNode>,
) -> Result<()> {
    if cmd.len() != 1 {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "CONFLICT needs a single keyword.",
        ));
    }
    paops.runtime.level += 1;
    pstack.push(Frame::Conflict {
        keyw: cmd[0].to_owned(),
        outer: std::mem::take(text),
        ours: Vec::new(),
        mode: ConflictMode::Ours,
    });
    Ok(())
}

/// `OURS` mode-switch inside a CONFLICT block. Anything collected
/// before OURS (rare — usually CONFLICT is immediately followed by
/// OURS) becomes part of the ours side, then the mode flips and
/// collection continues into `ours`. After THEIRS, OURS is an error.
fn parse_ours(
    line: &str,
    lineno: i32,
    paops: &mut ParseOps,
    pstack: &mut [Frame],
    text: &mut Vec<TextNode>,
) -> Result<()> {
    let Some(last) = pstack.last_mut() else {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "OURS outside of CONFLICT block.",
        ));
    };
    let Frame::Conflict { ours, mode, .. } = last else {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "OURS inside non-CONFLICT block.",
        ));
    };
    if *mode == ConflictMode::Theirs {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "OURS after THEIRS in CONFLICT block.",
        ));
    }
    // Re-attach the accumulated nodes to the ours side, then keep
    // collecting into ours via `text`. (When THEIRS arrives later it
    // will stash `text` into ours in turn.)
    ours.append(text);
    *mode = ConflictMode::Ours;
    Ok(())
}

/// `THEIRS` mode-switch inside a CONFLICT block. Stashes the
/// accumulated text into `ours` and starts collecting into `theirs`.
fn parse_theirs(
    line: &str,
    lineno: i32,
    paops: &mut ParseOps,
    pstack: &mut [Frame],
    text: &mut Vec<TextNode>,
) -> Result<()> {
    let Some(last) = pstack.last_mut() else {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "THEIRS outside of CONFLICT block.",
        ));
    };
    let Frame::Conflict { ours, mode, .. } = last else {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "THEIRS inside non-CONFLICT block.",
        ));
    };
    if *mode == ConflictMode::Theirs {
        return Err(parse_error(
            paops,
            lineno,
            line,
            "THEIRS after THEIRS in CONFLICT block.",
        ));
    }
    ours.append(text);
    *mode = ConflictMode::Theirs;
    Ok(())
}