odf-crypto 0.1.1

LibreOffice-faithful encryption for ODF packages (.odt, .ods, .odp): detect it, decrypt it, write it
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
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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
//! End-to-end tests for the `odf-crypto` binary.
//!
//! These drive the built binary as a subprocess rather than calling into the
//! library, because what is under test is argument handling, exit codes and
//! file side effects — none of which a library call exercises.
//!
//! Gated on the `cli` feature, which is what builds the binary at all.
//!
//! Exit-code coverage. Codes 0-6 are proven here against real fixtures; 6
//! (malformed) by `a_tampered_input_leaves_no_temp_and_no_target`, a golden
//! damaged past the window its password check covers. 7 (internal) is not:
//! it is unreachable by construction -- the `Internal` variants report an
//! invariant nothing can currently violate -- and 8 (host capacity) and 130
//! (Ctrl-C) need a starved host or a console signal. Their *mapping* is what
//! matters, and that is asserted directly in the binary's own unit tests
//! (`the_*_exit_map_is_the_documented_one`), which is sharper than
//! constructing a hostile fixture to reach the same line.
#![cfg(feature = "cli")]

use std::io::Write;
use std::path::{Path, PathBuf};
use std::process::{Command, Output, Stdio};

// Plan §3.
const EX_OK: i32 = 0;
const EX_USAGE: i32 = 1;
const EX_IO: i32 = 2;
const EX_NOT_ODF: i32 = 3;
const EX_WRONG_PASSWORD: i32 = 4;
const EX_REFUSED: i32 = 5;
const EX_MALFORMED: i32 = 6;

const PASSWORD: &str = "password";

/// `CARGO_BIN_EXE_<name>` is set by Cargo for every binary target when building
/// an integration test, so this needs no path guessing and no `cargo run`.
fn bin() -> &'static str {
    env!("CARGO_BIN_EXE_odf-crypto")
}

fn goldens() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/goldens")
}

fn golden(name: &str) -> PathBuf {
    goldens().join(name)
}

fn run(args: &[&str]) -> Output {
    Command::new(bin())
        .args(args)
        .stdin(Stdio::null())
        .output()
        .expect("binary runs")
}

fn code(out: &Output) -> i32 {
    out.status.code().expect("process exited normally")
}

fn stdout(out: &Output) -> String {
    String::from_utf8_lossy(&out.stdout).into_owned()
}

fn stderr(out: &Output) -> String {
    String::from_utf8_lossy(&out.stderr).into_owned()
}

/// A scratch directory that removes itself, so a failing test does not leave
/// `.odt` files in the repo. No `tempfile` dev-dependency for four tests.
struct Scratch(PathBuf);

impl Scratch {
    fn new(tag: &str) -> Self {
        let mut d = std::env::temp_dir();
        d.push(format!("odf-crypto-cli-{tag}-{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&d);
        std::fs::create_dir_all(&d).expect("scratch dir");
        Scratch(d)
    }
    fn join(&self, name: &str) -> PathBuf {
        self.0.join(name)
    }
}

impl Drop for Scratch {
    fn drop(&mut self) {
        let _ = std::fs::remove_dir_all(&self.0);
    }
}

// --- S1: help, version, classify, exit codes ------------------------------

#[test]
fn help_and_version_exit_zero_and_name_the_subcommands() {
    for flag in ["--help", "-h"] {
        let out = run(&[flag]);
        assert_eq!(code(&out), EX_OK, "{flag}");
        let s = stdout(&out);
        for cmd in ["classify", "decrypt", "encrypt"] {
            assert!(s.contains(cmd), "{flag} output must name `{cmd}`");
        }
    }
    for flag in ["--version", "-V"] {
        let out = run(&[flag]);
        assert_eq!(code(&out), EX_OK);
        assert!(stdout(&out).contains(env!("CARGO_PKG_VERSION")));
    }
}

#[test]
fn every_subcommand_has_its_own_help() {
    for cmd in ["classify", "decrypt", "encrypt"] {
        let out = run(&[cmd, "--help"]);
        assert_eq!(code(&out), EX_OK, "{cmd} --help");
        assert!(stdout(&out).contains(cmd));
    }
}

#[test]
fn classify_reports_the_algorithm_tuple() {
    let out = run(&[
        "classify",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_OK);
    let s = stdout(&out);
    assert!(s.contains("mode:        wholesome"), "{s}");
    assert!(s.contains("encrypted:   yes"), "{s}");
    assert!(s.contains("AES-GCM (W3C)"), "{s}");
    assert!(s.contains("Argon2id t=3 m=65536KiB p=4"), "{s}");
}

#[test]
fn an_unencrypted_package_is_an_answer_not_a_failure() {
    let out = run(&["classify", golden("lo-unencrypted.odt").to_str().unwrap()]);
    assert_eq!(code(&out), EX_OK, "plain must exit 0");
    assert!(stdout(&out).contains("encrypted:   no"));
}

#[test]
fn a_non_odf_input_exits_not_odf() {
    let s = Scratch::new("notodf");
    let f = s.join("junk.bin");
    std::fs::write(&f, b"this is not a zip file").unwrap();
    let out = run(&["classify", f.to_str().unwrap()]);
    assert_eq!(code(&out), EX_NOT_ODF);
}

#[test]
fn an_unknown_flag_exits_usage_and_names_itself() {
    let out = run(&[
        "classify",
        "--frobnicate",
        golden("lo-unencrypted.odt").to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_USAGE);
    assert!(stderr(&out).contains("--frobnicate"), "{}", stderr(&out));
}

#[test]
fn an_unknown_subcommand_exits_usage() {
    assert_eq!(code(&run(&["frobnicate"])), EX_USAGE);
    assert_eq!(code(&run(&[])), EX_USAGE);
}

// --- S2: --json -----------------------------------------------------------

/// Every golden's `--json` must be parseable. Parsing is done by a tiny
/// structural check rather than a JSON dependency: balanced braces outside
/// strings, and every key quoted. It catches the failure mode a hand-written
/// serialiser actually has — an unescaped quote or a missing comma.
fn looks_like_one_json_object(s: &str) -> bool {
    let s = s.trim();
    if !(s.starts_with('{') && s.ends_with('}')) {
        return false;
    }
    let (mut depth, mut in_str, mut esc) = (0i32, false, false);
    for c in s.chars() {
        match (in_str, esc, c) {
            (true, true, _) => esc = false,
            (true, false, '\\') => esc = true,
            (true, false, '"') => in_str = false,
            (true, false, _) => {}
            (false, _, '"') => in_str = true,
            (false, _, '{') => depth += 1,
            (false, _, '}') => {
                depth -= 1;
                if depth < 0 {
                    return false;
                }
            }
            _ => {}
        }
    }
    depth == 0 && !in_str
}

#[test]
fn json_is_well_formed_for_every_golden() {
    let mut seen = 0;
    for entry in std::fs::read_dir(goldens()).expect("goldens dir") {
        let p = entry.expect("entry").path();
        if p.extension().and_then(|e| e.to_str()) != Some("odt") {
            continue;
        }
        seen += 1;
        let out = run(&["classify", "--json", p.to_str().unwrap()]);
        assert_eq!(code(&out), EX_OK, "{}", p.display());
        let s = stdout(&out);
        assert!(looks_like_one_json_object(&s), "{}: {s}", p.display());
        assert!(s.contains("\"mode\":"), "{}", p.display());
    }
    // Discovered at run time rather than hardcoded, but assert the corpus is
    // not silently empty -- a glob that matches nothing passes every test.
    assert!(
        seen >= 6,
        "expected at least six .odt goldens, found {seen}"
    );
}

#[test]
fn json_and_human_agree() {
    let f = golden("aoo-blowfish-pbkdf2.odt");
    let human = stdout(&run(&["classify", f.to_str().unwrap()]));
    let json = stdout(&run(&["classify", "--json", f.to_str().unwrap()]));
    assert!(human.contains("per-entry") && json.contains("\"mode\":\"per-entry\""));
    assert!(human.contains("Blowfish-CFB") && json.contains("\"cipher\":\"Blowfish-CFB\""));
}

// --- S3: password sourcing ------------------------------------------------

#[test]
fn password_env_decrypts() {
    let s = Scratch::new("penv");
    let out = Command::new(bin())
        .args([
            "decrypt",
            golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
            "-o",
            s.join("out.odt").to_str().unwrap(),
            "--password-env",
            "ODF_CLI_TEST_PW",
        ])
        .env("ODF_CLI_TEST_PW", PASSWORD)
        .stdin(Stdio::null())
        .output()
        .expect("runs");
    assert_eq!(out.status.code(), Some(EX_OK), "{}", stderr(&out));
    assert!(s.join("out.odt").exists());
}

#[test]
fn password_file_decrypts_and_tolerates_a_trailing_newline() {
    let s = Scratch::new("pfile");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, format!("{PASSWORD}\n")).unwrap();
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        s.join("out.odt").to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_OK, "{}", stderr(&out));
}

#[test]
fn password_stdin_decrypts() {
    let s = Scratch::new("pstdin");
    let mut child = Command::new(bin())
        .args([
            "decrypt",
            golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
            "-o",
            s.join("out.odt").to_str().unwrap(),
            "--password-stdin",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn");
    child
        .stdin
        .take()
        .expect("stdin")
        .write_all(format!("{PASSWORD}\n").as_bytes())
        .expect("write password");
    let out = child.wait_with_output().expect("wait");
    assert_eq!(out.status.code(), Some(EX_OK), "{}", stderr(&out));
}

#[test]
fn two_password_sources_is_a_usage_error() {
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "--password-stdin",
        "--password-env",
        "ODF_CLI_TEST_PW",
    ]);
    assert_eq!(code(&out), EX_USAGE);
}

#[test]
fn no_password_source_without_a_tty_fails_rather_than_hanging() {
    // stdin is /dev/null via Stdio::null(), so a prompt would block forever.
    // The point of the test is that it returns at all.
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_USAGE);
    let e = stderr(&out);
    assert!(e.contains("--password-env"), "{e}");
    assert!(e.contains("--password-file"), "{e}");
    assert!(e.contains("--password-stdin"), "{e}");
}

#[test]
fn there_is_no_password_value_flag() {
    // Plan §2. argv is world-readable in a process listing, so the flag must
    // not exist -- and a caller reaching for it is told why, not just "unknown".
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "--password",
        PASSWORD,
    ]);
    assert_eq!(code(&out), EX_USAGE);
    assert!(stderr(&out).contains("world-readable"), "{}", stderr(&out));

    // And it is never advertised as an option in any help output.
    for args in [
        vec!["--help"],
        vec!["classify", "--help"],
        vec!["decrypt", "--help"],
        vec!["encrypt", "--help"],
    ] {
        for line in stdout(&run(&args)).lines() {
            let t = line.trim_start();
            assert!(
                !(t.starts_with("--password ") || t.starts_with("--password=")),
                "{args:?} defines a --password option: {line:?}"
            );
        }
    }
}

// --- S4: decrypt and encrypt ----------------------------------------------

fn decrypt_to(s: &Scratch, input: &Path, out_name: &str) -> Output {
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    run(&[
        "decrypt",
        input.to_str().unwrap(),
        "-o",
        s.join(out_name).to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ])
}

#[test]
fn decrypt_of_every_encrypted_golden_yields_a_plain_package() {
    let s = Scratch::new("decall");
    let mut seen = 0;
    for name in [
        "lo-wholesome-gcm-argon2.odt",
        "lo-legacy-aes-cbc.odt",
        "aoo-blowfish-pbkdf2.odt",
    ] {
        seen += 1;
        let out_name = format!("{name}.out");
        let out = decrypt_to(&s, &golden(name), &out_name);
        assert_eq!(out.status.code(), Some(EX_OK), "{name}: {}", stderr(&out));

        let check = run(&["classify", s.join(&out_name).to_str().unwrap()]);
        assert_eq!(check.status.code(), Some(EX_OK), "{name} reclassify");
        assert!(
            stdout(&check).contains("mode:        plain"),
            "{name} must decrypt to a plain package"
        );
    }
    assert_eq!(seen, 3);
}

#[test]
fn encrypt_then_decrypt_is_byte_identical() {
    let s = Scratch::new("round");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let src = golden("lo-unencrypted.odt");
    let sealed = s.join("sealed.odt");
    let back = s.join("back.odt");

    let e = run(&[
        "encrypt",
        src.to_str().unwrap(),
        "-o",
        sealed.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&e), EX_OK, "{}", stderr(&e));
    assert!(stdout(&run(&["classify", sealed.to_str().unwrap()])).contains("wholesome"));

    let d = run(&[
        "decrypt",
        sealed.to_str().unwrap(),
        "-o",
        back.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&d), EX_OK, "{}", stderr(&d));
    assert_eq!(
        std::fs::read(&src).unwrap(),
        std::fs::read(&back).unwrap(),
        "round trip must be byte-identical"
    );
}

#[test]
fn wrong_password_and_not_encrypted_have_different_exit_codes() {
    let s = Scratch::new("codes");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, "definitely not the password").unwrap();
    let wrong = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        s.join("x.odt").to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&wrong), EX_WRONG_PASSWORD);

    std::fs::write(&pw, PASSWORD).unwrap();
    let plain = run(&[
        "decrypt",
        golden("lo-unencrypted.odt").to_str().unwrap(),
        "-o",
        s.join("y.odt").to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&plain), EX_REFUSED);

    // The distinction the exit-code table exists for: "try again" is not the
    // same answer as "you had the wrong file".
    assert_ne!(code(&wrong), code(&plain));
}

#[test]
fn encrypting_an_already_encrypted_package_is_refused() {
    let s = Scratch::new("already");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let out = run(&[
        "encrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        s.join("x.odt").to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_REFUSED);
}

#[test]
fn an_existing_output_is_never_overwritten_without_force() {
    let s = Scratch::new("force");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let target = s.join("taken.odt");
    std::fs::write(&target, b"PRECIOUS").unwrap();

    let args = [
        "decrypt".to_string(),
        golden("lo-wholesome-gcm-argon2.odt")
            .to_str()
            .unwrap()
            .to_string(),
        "-o".to_string(),
        target.to_str().unwrap().to_string(),
        "--password-file".to_string(),
        pw.to_str().unwrap().to_string(),
    ];
    let refs: Vec<&str> = args.iter().map(String::as_str).collect();

    let out = run(&refs);
    assert_eq!(code(&out), EX_USAGE, "must refuse to clobber");
    assert_eq!(
        std::fs::read(&target).unwrap(),
        b"PRECIOUS",
        "the existing file must be untouched"
    );

    // With --force it proceeds, and leaves no temporary behind.
    let mut forced = refs.clone();
    forced.push("--force");
    let out = run(&forced);
    assert_eq!(code(&out), EX_OK, "{}", stderr(&out));
    assert_ne!(std::fs::read(&target).unwrap(), b"PRECIOUS");

    let leftovers: Vec<_> = std::fs::read_dir(&s.0)
        .unwrap()
        .filter_map(|e| e.ok())
        .map(|e| e.file_name().to_string_lossy().into_owned())
        .filter(|n| n.contains("odf-crypto.tmp"))
        .collect();
    assert!(leftovers.is_empty(), "temporary left behind: {leftovers:?}");
}

#[test]
fn the_default_output_name_is_derived_from_the_input() {
    let s = Scratch::new("derive");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    // Copy the golden into the scratch dir so the derived sibling lands there.
    let input = s.join("doc.odt");
    std::fs::copy(golden("lo-wholesome-gcm-argon2.odt"), &input).unwrap();

    let out = run(&[
        "decrypt",
        input.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_OK, "{}", stderr(&out));
    assert!(
        s.join("doc.decrypted.odt").exists(),
        "expected doc.decrypted.odt beside the input"
    );
}

#[test]
fn output_dash_writes_the_package_to_stdout() {
    let s = Scratch::new("stdout");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        "-",
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_OK, "{}", stderr(&out));
    // A zip local file header, so what landed on stdout is the package itself
    // and not a progress line.
    assert_eq!(&out.stdout[..2], b"PK", "stdout must carry the zip");
}

// --- coverage for the exit codes and paths the suite did not reach ---------

#[test]
fn a_missing_input_file_is_an_io_error() {
    let s = Scratch::new("missing");
    let out = run(&["classify", s.join("nope.odt").to_str().unwrap()]);
    assert_eq!(
        code(&out),
        EX_IO,
        "exit 2, not 'not-odf' -- the file is absent"
    );
    assert!(stderr(&out).contains("cannot read"), "{}", stderr(&out));
}

#[test]
fn a_missing_password_file_is_an_io_error() {
    let s = Scratch::new("nopw");
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        s.join("x.odt").to_str().unwrap(),
        "--password-file",
        s.join("nope").to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_IO);
}

#[test]
fn an_unset_password_env_var_is_a_usage_error() {
    // Usage, not I/O: the caller named a variable that does not exist, which is
    // a mistake in the invocation rather than a failure to read something.
    let s = Scratch::new("unsetenv");
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        s.join("x.odt").to_str().unwrap(),
        "--password-env",
        "ODF_CRYPTO_DEFINITELY_UNSET_VARIABLE",
    ]);
    assert_eq!(code(&out), EX_USAGE);
    assert!(stderr(&out).contains("is not set"), "{}", stderr(&out));
}

#[test]
fn an_empty_password_is_refused() {
    // A password file holding only a newline. first_line yields "", the library
    // rejects it as EmptyPassword, and that maps to refused rather than to
    // wrong-password -- it never got as far as trying a key.
    let s = Scratch::new("emptypw");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, "\n").unwrap();
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        s.join("x.odt").to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_REFUSED);
}

#[test]
fn a_truncated_package_is_not_odf() {
    let s = Scratch::new("trunc");
    let whole = std::fs::read(golden("lo-wholesome-gcm-argon2.odt")).unwrap();
    let f = s.join("trunc.odt");
    std::fs::write(&f, &whole[..400]).unwrap();
    let out = run(&["classify", f.to_str().unwrap()]);
    assert_eq!(
        code(&out),
        EX_NOT_ODF,
        "a truncated zip has no central directory"
    );
}

#[test]
fn a_near_miss_flag_is_given_a_suggestion() {
    // One of the two gaps that motivated moving to clap: the hand-rolled parser
    // said only "unrecognised option".
    let out = run(&[
        "decrypt",
        "--password-en",
        "X",
        golden("lo-unencrypted.odt").to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_USAGE);
    let e = stderr(&out);
    assert!(
        e.contains("--password-env"),
        "must suggest the real flag: {e}"
    );
}

#[test]
fn the_equals_form_works_end_to_end() {
    // The other gap: `--output=PATH` was rejected outright before clap.
    let s = Scratch::new("equals");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let target = s.join("eq.odt");
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        &format!("--output={}", target.display()),
        &format!("--password-file={}", pw.display()),
    ]);
    assert_eq!(code(&out), EX_OK, "{}", stderr(&out));
    assert!(target.exists(), "--output=PATH must be honoured");
}

#[test]
fn encrypt_also_accepts_a_piped_password() {
    // decrypt's stdin path is covered above; encrypt shares the code, so this
    // pins that the wiring is actually shared rather than duplicated.
    let s = Scratch::new("encstdin");
    let mut child = Command::new(bin())
        .args([
            "encrypt",
            golden("lo-unencrypted.odt").to_str().unwrap(),
            "-o",
            s.join("sealed.odt").to_str().unwrap(),
            "--password-stdin",
        ])
        .stdin(Stdio::piped())
        .stdout(Stdio::piped())
        .stderr(Stdio::piped())
        .spawn()
        .expect("spawn");
    child
        .stdin
        .take()
        .expect("stdin")
        .write_all(format!("{PASSWORD}\n").as_bytes())
        .expect("write");
    let out = child.wait_with_output().expect("wait");
    assert_eq!(out.status.code(), Some(EX_OK), "{}", stderr(&out));
    assert!(
        stdout(&run(&["classify", s.join("sealed.odt").to_str().unwrap()])).contains("wholesome")
    );
}

#[test]
fn no_subcommand_prints_help_and_exits_usage() {
    // clap's arg_required_else_help. Help on stdout is a courtesy; the exit code
    // still has to say the invocation was wrong, or a script cannot tell.
    let out = run(&[]);
    assert_eq!(code(&out), EX_USAGE);
}

// --- Argon2 cost flags: warn, never block ---

#[test]
fn weak_argon2_warns_on_stderr_and_still_writes() {
    // The project rule is warn, never block. Both halves are asserted here
    // because either alone would pass a broken implementation: a build that
    // warned and refused, and a build that wrote silently, each satisfy one.
    let s = Scratch::new("argonweak");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let src = golden("lo-unencrypted.odt");
    let out = s.join("weak.odt");

    let e = run(&[
        "encrypt",
        src.to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
        "--argon2-m",
        "8192",
    ]);

    assert_eq!(code(&e), EX_OK, "a weak tuple must not be refused");
    assert!(out.exists(), "the file must actually be written");
    let err = stderr(&e);
    assert!(
        err.contains("warning") && err.contains("weaker than"),
        "expected a weakness warning, got: {err}"
    );
    // The warning must name the consequence, not merely the fact.
    assert!(
        err.contains("every future reader"),
        "the warning should say the cost travels with the file: {err}"
    );
}

#[test]
fn default_argon2_writes_without_a_warning() {
    // Guards the inverse: if `is_weaker_than_libreoffice` were inverted, or
    // the default tuple drifted below its own constant, every encrypt would
    // start nagging and the warning would stop meaning anything.
    let s = Scratch::new("argondefault");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let src = golden("lo-unencrypted.odt");
    let out = s.join("default.odt");

    let e = run(&[
        "encrypt",
        src.to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
    ]);

    assert_eq!(code(&e), EX_OK, "{}", stderr(&e));
    assert!(
        !stderr(&e).contains("warning"),
        "the default tuple must not warn: {}",
        stderr(&e)
    );
}

#[test]
fn an_unrunnable_argon2_tuple_is_a_usage_error_not_a_malformed_file() {
    // m < 8p is argon2's own requirement. Exit 1 (usage) rather than 6
    // (malformed): the caller typed a bad flag, the document is fine, and a
    // script must be able to tell those apart.
    let s = Scratch::new("argonbad");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let src = golden("lo-unencrypted.odt");
    let out = s.join("never.odt");

    let e = run(&[
        "encrypt",
        src.to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
        "--argon2-m",
        "8",
        "--argon2-p",
        "4",
    ]);

    assert_eq!(code(&e), EX_USAGE, "{}", stderr(&e));
    assert!(
        !out.exists(),
        "nothing should be written on a refused tuple"
    );
    // The message must name WHOSE rule was broken, not just that one was.
    // Reporting a bound of ours as a rule of the format is the failure this
    // taxonomy exists to prevent, and it is invisible unless asserted.
    let err = stderr(&e);
    assert!(err.contains("argon2 itself requires"), "{err}");
    assert!(
        !err.contains("this crate acts on"),
        "m < 8p is argon2's requirement, not our policy bound: {err}"
    );
}

#[test]
fn each_argon2_axis_defaults_independently() {
    // `--argon2-m` alone must keep LibreOffice's t and p rather than zeroing
    // them, which is the obvious way to get this wrong.
    let s = Scratch::new("argonaxis");
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let src = golden("lo-unencrypted.odt");
    let out = s.join("axis.odt");

    let e = run(&[
        "encrypt",
        src.to_str().unwrap(),
        "-o",
        out.to_str().unwrap(),
        "--password-file",
        pw.to_str().unwrap(),
        "--argon2-m",
        "16384",
    ]);
    assert_eq!(code(&e), EX_OK, "{}", stderr(&e));

    let c = run(&["classify", out.to_str().unwrap(), "--json"]);
    let json = stdout(&c);
    assert!(
        json.contains("\"kdf\": \"Argon2id t=3 m=16384KiB p=4\"")
            || json.contains("\"kdf\":\"Argon2id t=3 m=16384KiB p=4\""),
        "t and p should still be LibreOffice's: {json}"
    );
}

// --- rekey, and what a failed run leaves behind (#94) -----------------------

/// Every file in `s` whose name marks it as this binary's temporary output.
fn temps_in(s: &Scratch) -> Vec<String> {
    std::fs::read_dir(&s.0)
        .unwrap()
        .map(|e| e.unwrap().file_name().to_string_lossy().into_owned())
        .filter(|n| n.ends_with(".odf-crypto.tmp"))
        .collect()
}

fn rekey(s: &Scratch, input: &Path, out_name: &str, old: &str, new: &str) -> Output {
    Command::new(bin())
        .args([
            "rekey",
            input.to_str().unwrap(),
            "-o",
            s.join(out_name).to_str().unwrap(),
            "--password-env",
            "ODF_CLI_OLD",
            "--new-password-env",
            "ODF_CLI_NEW",
            "--argon2-t",
            "1",
            "--argon2-m",
            "8",
            "--argon2-p",
            "1",
        ])
        .env("ODF_CLI_OLD", old)
        .env("ODF_CLI_NEW", new)
        .stdin(Stdio::null())
        .output()
        .expect("runs")
}

/// `rekey` writes a package the new password opens and the old one does not,
/// holding exactly what the old one held -- for both source shapes.
#[test]
fn rekey_changes_the_password() {
    let s = Scratch::new("rekey");
    for name in ["lo-wholesome-gcm-argon2.odt", "lo-legacy-aes-cbc.odt"] {
        let out = rekey(&s, &golden(name), "rekeyed.odt", PASSWORD, "brand new");
        assert_eq!(code(&out), EX_OK, "{name}: {}", stderr(&out));
        let before = decrypt_to(&s, &golden(name), "before.odt");
        assert_eq!(code(&before), EX_OK);

        let pw = s.join("new.txt");
        std::fs::write(&pw, "brand new").unwrap();
        let after = run(&[
            "decrypt",
            s.join("rekeyed.odt").to_str().unwrap(),
            "-o",
            s.join("after.odt").to_str().unwrap(),
            "--password-file",
            pw.to_str().unwrap(),
        ]);
        assert_eq!(code(&after), EX_OK, "{name}: {}", stderr(&after));
        let old = decrypt_to(&s, &s.join("rekeyed.odt"), "old.odt");
        assert_eq!(
            code(&old),
            EX_WRONG_PASSWORD,
            "{name}: the old password still opens it"
        );
        if name.starts_with("lo-wholesome") {
            // A wholesome re-key carries the inner package over byte for byte.
            assert_eq!(
                std::fs::read(s.join("after.odt")).unwrap(),
                std::fs::read(s.join("before.odt")).unwrap(),
                "{name}"
            );
        }
        for f in ["rekeyed.odt", "before.odt", "after.odt"] {
            let _ = std::fs::remove_file(s.join(f));
        }
        assert!(temps_in(&s).is_empty(), "{name}: {:?}", temps_in(&s));
    }
}

/// A per-entry package with a member its manifest does not list: `rekey`
/// refuses it with exit 5 and leaves neither a temporary file nor a target.
#[test]
fn a_refused_rekey_leaves_no_temp_and_no_target() {
    let s = Scratch::new("rekey-refused");
    let src = s.join("unlisted.odt");
    {
        let golden_bytes = std::fs::read(golden("aoo-blowfish-pbkdf2.odt")).unwrap();
        let mut zin = zip::ZipArchive::new(std::io::Cursor::new(golden_bytes)).unwrap();
        let mut zout = zip::ZipWriter::new(std::fs::File::create(&src).unwrap());
        for i in 0..zin.len() {
            zout.raw_copy_file(zin.by_index_raw(i).unwrap()).unwrap();
        }
        let stored = zip::write::SimpleFileOptions::default()
            .compression_method(zip::CompressionMethod::Stored);
        zout.start_file("unlisted.xml", stored).unwrap();
        zout.write_all(b"<x/>").unwrap();
        zout.finish().unwrap();
    }
    let out = rekey(&s, &src, "rekeyed.odt", PASSWORD, "brand new");
    assert_eq!(code(&out), EX_REFUSED, "{}", stderr(&out));
    assert!(
        !s.join("rekeyed.odt").exists(),
        "a refused rekey wrote its target"
    );
    assert!(temps_in(&s).is_empty(), "left behind: {:?}", temps_in(&s));
}

/// A wrong old password: exit 4, nothing left behind.
#[test]
fn a_wrong_old_password_leaves_no_temp_and_no_target() {
    let s = Scratch::new("rekey-wrong");
    let out = rekey(
        &s,
        &golden("lo-legacy-aes-cbc.odt"),
        "rekeyed.odt",
        "wrong",
        "new",
    );
    assert_eq!(code(&out), EX_WRONG_PASSWORD, "{}", stderr(&out));
    assert!(!s.join("rekeyed.odt").exists());
    assert!(temps_in(&s).is_empty(), "left behind: {:?}", temps_in(&s));
}

/// Tampered past the window the password check covers: the checked 1 KiB
/// passes, plaintext is already on its way to the temporary file, and the
/// member then fails to inflate. That partial plaintext must not survive --
/// not as a temporary file, and not as the target.
#[test]
fn a_tampered_input_leaves_no_temp_and_no_target() {
    let s = Scratch::new("tampered");
    let mut bytes = std::fs::read(golden("lo-legacy-aes-cbc.odt")).unwrap();
    let at = {
        let mut z = zip::ZipArchive::new(std::io::Cursor::new(&bytes)).unwrap();
        let f = z.by_name("content.xml").unwrap();
        assert!(
            f.compressed_size() > 1300,
            "content.xml must outrun the checked window"
        );
        (f.data_start().unwrap() + 1200) as usize
    };
    bytes[at] ^= 0x5a;
    let src = s.join("tampered.odt");
    std::fs::write(&src, &bytes).unwrap();

    let out = decrypt_to(&s, &src, "out.odt");
    assert_eq!(code(&out), EX_MALFORMED, "{}", stderr(&out));
    assert!(
        !s.join("out.odt").exists(),
        "a failed decrypt wrote its target"
    );
    assert!(temps_in(&s).is_empty(), "left behind: {:?}", temps_in(&s));
}

/// `encrypt` and `rekey` to stdout must seek while writing, so they go through
/// a scratch file -- which is gone once the run ends.
#[test]
fn encrypt_and_rekey_to_stdout_leave_no_scratch_file() {
    for (verb, input) in [
        ("encrypt", "lo-unencrypted.odt"),
        ("rekey", "lo-wholesome-gcm-argon2.odt"),
    ] {
        let mut cmd = Command::new(bin());
        cmd.arg(verb)
            .arg(golden(input))
            .args(["-o", "-", "--password-env", "ODF_CLI_OLD"])
            .args(["--argon2-t", "1", "--argon2-m", "8", "--argon2-p", "1"])
            .env("ODF_CLI_OLD", PASSWORD)
            .env("ODF_CLI_NEW", "brand new")
            .stdin(Stdio::null())
            .stdout(Stdio::piped())
            .stderr(Stdio::piped());
        if verb == "rekey" {
            cmd.args(["--new-password-env", "ODF_CLI_NEW"]);
        }
        let child = cmd.spawn().expect("runs");
        let pid = child.id();
        let out = child.wait_with_output().unwrap();
        assert_eq!(code(&out), EX_OK, "{verb}: {}", stderr(&out));
        assert_eq!(&out.stdout[..2], b"PK", "{verb}: stdout must carry the zip");
        let scratch = std::env::temp_dir().join(format!("odf-crypto-{pid}.tmp"));
        assert!(!scratch.exists(), "{verb}: left {scratch:?}");
    }
}

/// On Unix the temporary file takes the target's mode before a byte is
/// written, so `--force` over a 0600 file leaves a 0600 file.
#[cfg(unix)]
#[test]
fn an_overwritten_target_keeps_its_permissions() {
    use std::os::unix::fs::PermissionsExt;
    let s = Scratch::new("perms");
    let target = s.join("out.odt");
    std::fs::write(&target, b"old").unwrap();
    std::fs::set_permissions(&target, std::fs::Permissions::from_mode(0o600)).unwrap();
    let pw = s.join("pw.txt");
    std::fs::write(&pw, PASSWORD).unwrap();
    let out = run(&[
        "decrypt",
        golden("lo-wholesome-gcm-argon2.odt").to_str().unwrap(),
        "-o",
        target.to_str().unwrap(),
        "--force",
        "--password-file",
        pw.to_str().unwrap(),
    ]);
    assert_eq!(code(&out), EX_OK, "{}", stderr(&out));
    let mode = std::fs::metadata(&target).unwrap().permissions().mode() & 0o777;
    assert_eq!(mode, 0o600);
}