enprot 0.5.44

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
// 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.

//! Conflict resolver (TODO.roadmap/44).
//!
//! `enprot resolve [--ours|--theirs|--both|--interactive] FILE` walks
//! a parsed tree and replaces every [`TextNode::Conflict`] with the
//! caller-chosen resolution. Non-interactive modes (`--ours`,
//! `--theirs`, `--both`) apply one decision to every conflict;
//! interactive mode prompts per conflict and requires a TTY.
//!
//! The output is always valid EPT — conflict markers are fully
//! removed (or replaced with explicit BeginEnd copies of the chosen
//! side). Re-running `enprot resolve` on a clean file is a no-op.

use std::io::{BufRead, Write};

use crate::error::{Error, Result};
use crate::etree::{TextNode, TextTree};

/// How to resolve a single conflict.
#[derive(Copy, Clone, Debug, Eq, PartialEq)]
pub enum ResolveMode {
    /// Keep the `ours` side; drop theirs.
    Ours,
    /// Keep the `theirs` side; drop ours.
    Theirs,
    /// Concatenate: ours then theirs, both as BeginEnd blocks under
    /// the original keyw. Useful when both edits carry distinct
    /// information the caller wants to preserve.
    Both,
    /// Drop the conflict entirely. The WORD region is removed from
    /// the output. Caller must understand the data-loss implication.
    Skip,
    /// Prompt for each conflict.
    Interactive,
}

impl ResolveMode {
    pub fn from_cli_flag(s: &str) -> Result<Self> {
        match s.to_ascii_lowercase().as_str() {
            "ours" => Ok(ResolveMode::Ours),
            "theirs" => Ok(ResolveMode::Theirs),
            "both" => Ok(ResolveMode::Both),
            "skip" => Ok(ResolveMode::Skip),
            "interactive" | "i" => Ok(ResolveMode::Interactive),
            other => Err(Error::InvalidArg {
                arg: "--mode",
                reason: format!(
                    "unknown resolve mode '{other}' (expected: ours, theirs, both, skip, interactive)"
                ),
            }),
        }
    }
}

/// Resolve every Conflict in `tree` according to `mode`. Returns the
/// cleaned tree and the number of conflicts that were resolved.
pub fn resolve_tree(tree: &TextTree, mode: ResolveMode) -> Result<(TextTree, usize)> {
    resolve_tree_with_overrides(tree, mode, &WordOverride::default())
}

/// Per-WORD override map for [`resolve_tree`]. Words not in the map
/// fall back to the global mode. (TODO.roadmap/56.)
#[derive(Default, Clone, Debug)]
pub struct WordOverride {
    overrides: std::collections::HashMap<String, ResolveMode>,
}

impl WordOverride {
    /// Parse `WORD:MODE` strings into an override map. Malformed
    /// entries surface as `Err`. Unknown mode values surface as
    /// `Err`. Repeated WORDs overwrite (last wins).
    pub fn from_cli_flags(flags: &[String]) -> Result<Self> {
        let mut overrides = std::collections::HashMap::new();
        for f in flags {
            let (word, mode_str) = f.split_once(':').ok_or_else(|| Error::InvalidArg {
                arg: "--word",
                reason: format!("--word value must be WORD:MODE, got '{f}'"),
            })?;
            if word.is_empty() {
                return Err(Error::InvalidArg {
                    arg: "--word",
                    reason: format!("--word value '{f}' has empty WORD"),
                });
            }
            let mode = ResolveMode::from_cli_flag(mode_str)?;
            if matches!(mode, ResolveMode::Interactive) {
                return Err(Error::InvalidArg {
                    arg: "--word",
                    reason: format!(
                        "--word {word}:interactive not supported (interactive prompts only via --mode)"
                    ),
                });
            }
            overrides.insert(word.to_string(), mode);
        }
        Ok(WordOverride { overrides })
    }

    /// Look up the override for `word`, if any.
    pub fn get(&self, word: &str) -> Option<ResolveMode> {
        self.overrides.get(word).copied()
    }
}

/// Resolve every Conflict with a global mode plus per-WORD overrides.
/// The override wins when present; otherwise the global mode applies.
pub fn resolve_tree_with_overrides(
    tree: &TextTree,
    mode: ResolveMode,
    overrides: &WordOverride,
) -> Result<(TextTree, usize)> {
    let mut count = 0;
    let mut out = Vec::with_capacity(tree.len());
    for node in tree {
        match node {
            TextNode::Conflict { keyw, ours, theirs } => {
                let pick = if let Some(ov) = overrides.get(keyw) {
                    ov
                } else {
                    match mode {
                        ResolveMode::Interactive => prompt_one(keyw, ours, theirs)?,
                        other => other,
                    }
                };
                count += 1;
                emit_resolution(&mut out, keyw, ours, theirs, pick);
            }
            other => out.push(other.clone()),
        }
    }
    Ok((out, count))
}

fn emit_resolution(
    out: &mut TextTree,
    keyw: &str,
    ours: &TextTree,
    theirs: &TextTree,
    pick: ResolveMode,
) {
    match pick {
        ResolveMode::Ours => out.extend_from_slice(ours),
        ResolveMode::Theirs => out.extend_from_slice(theirs),
        ResolveMode::Both => {
            out.extend_from_slice(ours);
            out.extend_from_slice(theirs);
        }
        ResolveMode::Skip | ResolveMode::Interactive => {
            // Skip drops both. Interactive was already resolved to
            // one of the above by prompt_one; reaching here under
            // Interactive means the user chose Skip.
            let _ = (keyw, ours, theirs);
        }
    }
}

/// Prompt the user for one conflict's resolution. Reads from `stdin`.
fn prompt_one(keyw: &str, ours: &TextTree, theirs: &TextTree) -> Result<ResolveMode> {
    let stdin = std::io::stdin();
    let mut stdout = std::io::stdout();
    writeln!(
        stdout,
        "CONFLICT on WORD {} — choose resolution [o/ours, t/theirs, b/both, s/skip]:",
        keyw
    )?;
    writeln!(stdout, "  -- ours --")?;
    print_tree(&mut stdout, ours, "    ")?;
    writeln!(stdout, "  -- theirs --")?;
    print_tree(&mut stdout, theirs, "    ")?;
    write!(stdout, "> ")?;
    stdout.flush()?;

    let mut buf = String::new();
    stdin.lock().read_line(&mut buf)?;
    let trimmed = buf.trim().to_ascii_lowercase();
    match trimmed.as_str() {
        "o" | "ours" => Ok(ResolveMode::Ours),
        "t" | "theirs" => Ok(ResolveMode::Theirs),
        "b" | "both" => Ok(ResolveMode::Both),
        "s" | "skip" | "" => Ok(ResolveMode::Skip),
        other => Err(Error::InvalidArg {
            arg: "<interactive>",
            reason: format!("unknown response '{other}' (expected: o, t, b, s)"),
        }),
    }
}

fn print_tree<W: Write>(out: &mut W, tree: &TextTree, indent: &str) -> Result<()> {
    for node in tree {
        match node {
            TextNode::Plain(s) => writeln!(out, "{}{}", indent, s)?,
            TextNode::Data(d) => writeln!(out, "{}<{} data bytes>", indent, d.len())?,
            TextNode::Stored { keyw, cas } => writeln!(
                out,
                "{}STORED {} {}",
                indent,
                keyw,
                &cas[..cas.len().min(16)]
            )?,
            TextNode::Encrypted { keyw, .. } => writeln!(out, "{}ENCRYPTED {}", indent, keyw)?,
            TextNode::BeginEnd { keyw, .. } => writeln!(out, "{}BEGIN/END {}", indent, keyw)?,
            TextNode::Chain { .. } => writeln!(out, "{}CHAIN", indent)?,
            TextNode::Include { hash } => {
                writeln!(out, "{}INCLUDE {}", indent, &hash[..hash.len().min(16)])?
            }
            TextNode::Conflict { keyw, .. } => writeln!(out, "{}CONFLICT {}", indent, keyw)?,
            TextNode::Immutable { name, hashalg, .. } => {
                writeln!(out, "{}IMMUTABLE {} {}=…", indent, name, hashalg)?
            }
            TextNode::Muted { name, .. } => writeln!(out, "{}MUTED {}", indent, name)?,
            TextNode::Key { name, .. } => writeln!(out, "{}KEY {}", indent, name)?,
            TextNode::Unkey { name } => writeln!(out, "{}UNKEY {}", indent, name)?,
            TextNode::Cert { name, .. } => writeln!(out, "{}CERT {}", indent, name)?,
            TextNode::Uncert { name } => writeln!(out, "{}UNCERT {}", indent, name)?,
        }
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::etree::ParseOps;
    use std::io::Cursor;

    fn parse_str(s: &str) -> TextTree {
        let mut paops = ParseOps::new(crate::crypto::default_policy()).unwrap();
        crate::etree::parse(Cursor::new(s.as_bytes()), &mut paops).unwrap()
    }

    fn conflict_tree() -> TextTree {
        parse_str(
            "// <( CONFLICT X )>\n// <( OURS )>\n// <( BEGIN X )>\nhi-our\n// <( END X )>\n// <( THEIRS )>\n// <( BEGIN X )>\nhi-their\n// <( END X )>\n// <( END X )>\n",
        )
    }

    #[test]
    fn resolve_ours_drops_theirs_and_markers() {
        let t = conflict_tree();
        let (resolved, n) = resolve_tree(&t, ResolveMode::Ours).unwrap();
        assert_eq!(n, 1);
        // No Conflict node remains.
        assert!(
            !resolved
                .iter()
                .any(|n| matches!(n, TextNode::Conflict { .. }))
        );
        // Ours content survives.
        assert!(
            resolved
                .iter()
                .any(|n| matches!(n, TextNode::BeginEnd { keyw, .. } if keyw == "X"))
        );
    }

    #[test]
    fn resolve_theirs_drops_ours() {
        let t = conflict_tree();
        let (resolved, _) = resolve_tree(&t, ResolveMode::Theirs).unwrap();
        assert!(
            !resolved
                .iter()
                .any(|n| matches!(n, TextNode::Conflict { .. }))
        );
    }

    #[test]
    fn resolve_both_keeps_both_sides() {
        let t = conflict_tree();
        let (resolved, _) = resolve_tree(&t, ResolveMode::Both).unwrap();
        // Both copies of X appear.
        let x_count = resolved
            .iter()
            .filter(|n| matches!(n, TextNode::BeginEnd { keyw, .. } if keyw == "X"))
            .count();
        assert_eq!(x_count, 2);
    }

    #[test]
    fn resolve_skip_drops_everything() {
        let t = conflict_tree();
        let (resolved, _) = resolve_tree(&t, ResolveMode::Skip).unwrap();
        // No X anywhere.
        assert!(
            !resolved
                .iter()
                .any(|n| matches!(n, TextNode::BeginEnd { keyw, .. } if keyw == "X"))
        );
    }

    #[test]
    fn resolve_on_clean_tree_is_noop() {
        let t = parse_str("// <( BEGIN X )>\nbody\n// <( END X )>\n");
        let (resolved, n) = resolve_tree(&t, ResolveMode::Ours).unwrap();
        assert_eq!(n, 0);
        assert_eq!(resolved, t);
    }

    #[test]
    fn mode_from_cli_flag_round_trips() {
        assert_eq!(
            ResolveMode::from_cli_flag("ours").unwrap(),
            ResolveMode::Ours
        );
        assert_eq!(
            ResolveMode::from_cli_flag("THEIRS").unwrap(),
            ResolveMode::Theirs
        );
        assert!(ResolveMode::from_cli_flag("garbage").is_err());
    }

    #[test]
    fn word_override_parses_valid_flags() {
        let ov = WordOverride::from_cli_flags(&[
            "Agent_007:ours".into(),
            "GEHEIM:theirs".into(),
            "PUBLIC:both".into(),
        ])
        .unwrap();
        assert_eq!(ov.get("Agent_007"), Some(ResolveMode::Ours));
        assert_eq!(ov.get("GEHEIM"), Some(ResolveMode::Theirs));
        assert_eq!(ov.get("PUBLIC"), Some(ResolveMode::Both));
        assert_eq!(ov.get("UNLISTED"), None);
    }

    #[test]
    fn word_override_rejects_malformed_flags() {
        assert!(WordOverride::from_cli_flags(&["no-colon".into()]).is_err());
        assert!(WordOverride::from_cli_flags(&[":ours".into()]).is_err());
        assert!(WordOverride::from_cli_flags(&["X:bogus".into()]).is_err());
        // Interactive isn't allowed as a per-WORD override — the
        // prompt path only fires via --mode.
        assert!(WordOverride::from_cli_flags(&["X:interactive".into()]).is_err());
    }

    #[test]
    fn resolve_per_word_override_wins_over_global_mode() {
        let t = parse_str(
            "// <( CONFLICT X )>\n// <( OURS )>\n// <( BEGIN X )>\nhi-our\n// <( END X )>\n// <( THEIRS )>\n// <( BEGIN X )>\nhi-their\n// <( END X )>\n// <( END X )>\n// <( CONFLICT Y )>\n// <( OURS )>\n// <( BEGIN Y )>\nyo-our\n// <( END Y )>\n// <( THEIRS )>\n// <( BEGIN Y )>\nyo-their\n// <( END Y )>\n// <( END Y )>\n",
        );
        let ov = WordOverride::from_cli_flags(&["X:ours".into()]).unwrap();
        let (resolved, _) = resolve_tree_with_overrides(&t, ResolveMode::Theirs, &ov).unwrap();
        // X takes ours (override wins).
        let body = serialize(&resolved);
        assert!(body.contains("hi-our") && !body.contains("hi-their"));
        // Y falls back to global mode (theirs).
        assert!(body.contains("yo-their") && !body.contains("yo-our"));
    }

    fn serialize(tree: &TextTree) -> String {
        let mut buf: Vec<u8> = Vec::new();
        let mut paops = ParseOps::new(crate::crypto::default_policy()).unwrap();
        crate::etree::tree_write(&mut buf, tree, &mut paops).unwrap();
        String::from_utf8(buf).unwrap()
    }
}

#[cfg(test)]
mod render_tests {
    use super::*;
    use crate::etree::TextNode;
    use std::collections::BTreeMap;

    /// print_tree renders every TextNode kind without panicking on
    /// short hashes (`&cas[..min(16)]` slicing) — one node of each
    /// variant, including hash values shorter than 16 chars.
    #[test]
    fn print_tree_renders_every_node_kind() {
        let tree: TextTree = vec![
            TextNode::Plain("plain text".into()),
            TextNode::Data(vec![1, 2, 3]),
            TextNode::Stored {
                keyw: "W".into(),
                cas: "short".into(), // shorter than 16 — slicing must not panic
            },
            TextNode::Encrypted {
                keyw: "W".into(),
                txt: vec![],
                extfields: BTreeMap::new(),
            },
            TextNode::BeginEnd {
                keyw: "W".into(),
                txt: vec![],
            },
            TextNode::Chain {
                extfields: BTreeMap::new(),
            },
            TextNode::Include {
                hash: "inc".into(), // shorter than 16
            },
            TextNode::Conflict {
                keyw: "W".into(),
                ours: vec![],
                theirs: vec![],
            },
            TextNode::Immutable {
                name: "L".into(),
                hashalg: "sha384".into(),
                hash: "AB".into(),
                txt: vec![],
            },
            TextNode::Muted {
                name: "L".into(),
                hashalg: "sha384".into(),
                hash: "AB".into(),
            },
            TextNode::Key {
                name: "k".into(),
                hashalg: "sha256".into(),
                hash: "11".into(),
            },
            TextNode::Unkey { name: "k".into() },
            TextNode::Cert {
                name: "c".into(),
                hashalg: "sha256".into(),
                hash: "22".into(),
            },
            TextNode::Uncert { name: "c".into() },
        ];
        let mut out = Vec::new();
        print_tree(&mut out, &tree, "  ").unwrap();
        let s = String::from_utf8(out).unwrap();
        assert!(s.contains("plain text"), "{s}");
        assert!(s.contains("<3 data bytes>"), "{s}");
        assert!(s.contains("STORED W short"), "{s}");
        assert!(s.contains("ENCRYPTED W"), "{s}");
        assert!(s.contains("BEGIN/END W"), "{s}");
        assert!(s.contains("CHAIN"), "{s}");
        assert!(s.contains("INCLUDE inc"), "{s}");
        assert!(s.contains("CONFLICT W"), "{s}");
        assert!(s.contains("IMMUTABLE L sha384=…"), "{s}");
        assert!(s.contains("MUTED L"), "{s}");
        assert!(s.contains("KEY k"), "{s}");
        assert!(s.contains("UNKEY k"), "{s}");
        assert!(s.contains("CERT c"), "{s}");
        assert!(s.contains("UNCERT c"), "{s}");
    }
}