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
//! Unit tests for the CLI's own logic — the parts that are not the library and
//! not clap.
//!
//! End-to-end behaviour (exit codes, argv handling, atomic writes) is exercised
//! by `tests/cli.rs`, which drives the built binary. What is tested here is the
//! pure helpers and the command definition, where a unit test is sharper than a
//! subprocess.

use super::*;

// Not added to the binary's own `use odf_crypto::{...}` list: the mapping
// functions match `HostCannotAllocate { .. }`, so only these tests name the
// site, and importing it there would be an unused import at `-D warnings`.
use odf_crypto::{classify, AllocationSite};

#[test]
fn the_command_definition_is_internally_consistent() {
    // clap's own audit: catches a duplicate id, a group naming an argument that
    // does not exist, a short flag used twice. Cheap, and it covers every
    // subcommand rather than only the paths a test happens to take.
    cli().debug_assert();
}

#[test]
fn derived_output_inserts_before_the_extension() {
    assert_eq!(
        derived_output(Path::new("report.odt"), "decrypted"),
        PathBuf::from("report.decrypted.odt")
    );
    assert_eq!(
        derived_output(Path::new("/tmp/a/report.ods"), "encrypted"),
        PathBuf::from("/tmp/a/report.encrypted.ods")
    );
}

#[test]
fn derived_output_appends_when_there_is_no_extension() {
    assert_eq!(
        derived_output(Path::new("report"), "decrypted"),
        PathBuf::from("report.decrypted")
    );
}

#[test]
fn derived_output_keeps_a_dotted_stem() {
    // `a.b.odt` has stem `a.b`; the suffix goes before the real extension only.
    assert_eq!(
        derived_output(Path::new("a.b.odt"), "decrypted"),
        PathBuf::from("a.b.decrypted.odt")
    );
}

#[test]
fn first_line_strips_one_trailing_newline_and_no_more() {
    assert_eq!(first_line("hunter2\n"), "hunter2");
    assert_eq!(first_line("hunter2\r\n"), "hunter2");
    assert_eq!(first_line("hunter2"), "hunter2");
    // Only the first line: a file with more in it is not a multi-line password.
    assert_eq!(first_line("hunter2\nignored\n"), "hunter2");
    // Trailing spaces can be deliberate, so they survive.
    assert_eq!(first_line("hunter2  \n"), "hunter2  ");
    assert_eq!(first_line(""), "");
}

#[test]
fn exit_codes_separate_try_again_from_wrong_file() {
    // The distinction the whole table exists for.
    assert_eq!(
        decrypt_exit(&DecryptError::WrongPassword),
        EX_WRONG_PASSWORD
    );
    assert_eq!(decrypt_exit(&DecryptError::NotEncrypted), EX_REFUSED);
    assert_ne!(EX_WRONG_PASSWORD, EX_REFUSED);
}

#[test]
fn exit_codes_map_each_error_class() {
    assert_eq!(detect_exit(&DetectError::NotZip), EX_NOT_ODF);
    assert_eq!(detect_exit(&DetectError::MissingManifest), EX_NOT_ODF);
    assert_eq!(
        detect_exit(&DetectError::Inconsistent(String::new())),
        EX_REFUSED
    );
    assert_eq!(detect_exit(&DetectError::Zip(String::new())), EX_MALFORMED);

    // A wrapped classify failure keeps the classify code rather than collapsing
    // to a generic decrypt failure.
    assert_eq!(
        decrypt_exit(&DecryptError::Classify(DetectError::NotZip)),
        EX_NOT_ODF
    );
    assert_eq!(decrypt_exit(&DecryptError::UnsupportedPgp), EX_REFUSED);
    assert_eq!(
        decrypt_exit(&DecryptError::Inflate(String::new())),
        EX_MALFORMED
    );
    assert_eq!(
        decrypt_exit(&DecryptError::Internal(String::new())),
        EX_INTERNAL
    );

    assert_eq!(encrypt_exit(&EncryptError::AlreadyEncrypted), EX_REFUSED);
    assert_eq!(
        encrypt_exit(&EncryptError::Classify(DetectError::MissingManifest)),
        EX_NOT_ODF
    );
    assert_eq!(
        encrypt_exit(&EncryptError::Internal(String::new())),
        EX_INTERNAL
    );
    assert_eq!(
        encrypt_exit(&EncryptError::Random(String::new())),
        EX_INTERNAL
    );
}

#[test]
fn exactly_one_password_source_is_accepted() {
    // clap's ArgGroup enforces it, so this pins the wiring rather than the rule.
    let two = cli().try_get_matches_from([
        "odf-crypto",
        "decrypt",
        "f.odt",
        "--password-stdin",
        "--password-env",
        "PW",
    ]);
    assert!(two.is_err(), "two password sources must be rejected");

    for one in [
        vec!["odf-crypto", "decrypt", "f.odt", "--password-stdin"],
        vec!["odf-crypto", "decrypt", "f.odt", "--password-env", "PW"],
        vec!["odf-crypto", "decrypt", "f.odt", "--password-file", "p"],
        // None is legal: it means "prompt".
        vec!["odf-crypto", "decrypt", "f.odt"],
    ] {
        assert!(
            cli().try_get_matches_from(&one).is_ok(),
            "{one:?} must parse"
        );
    }
}

#[test]
fn the_equals_form_parses() {
    // The gap that motivated moving to clap: `--output=x.odt` was rejected
    // outright by the hand-rolled parser this replaced.
    let m = cli()
        .try_get_matches_from(["odf-crypto", "decrypt", "f.odt", "--output=x.odt"])
        .expect("--flag=value must parse");
    let sub = m.subcommand_matches("decrypt").expect("decrypt");
    assert_eq!(
        sub.get_one::<String>("output").map(String::as_str),
        Some("x.odt")
    );
}

#[test]
fn the_password_argument_is_hidden_but_recognised() {
    // Plan §2. It parses -- so `cmd_crypt` can explain *why* it does not exist,
    // rather than clap reporting a generic unexpected argument -- and it never
    // appears in help, so it is not offered.
    let m = cli()
        .try_get_matches_from(["odf-crypto", "decrypt", "f.odt", "--password", "secret"])
        .expect("the trap argument must parse");
    let sub = m.subcommand_matches("decrypt").expect("decrypt");
    assert_eq!(
        sub.get_one::<String>(PASSWORD_TRAP).map(String::as_str),
        Some("secret")
    );
    // And it is refused with an explanation, not acted on.
    assert_eq!(cmd_crypt(sub, Direction::Decrypt), EX_USAGE);
}

#[test]
fn no_help_output_ever_offers_a_password_value_argument() {
    // The predicate is "no line DEFINES the option", not "the string never
    // appears": the after-help text mentions `--password VALUE` precisely to say
    // it does not exist, and a substring check would fail on that prose.
    let mut cmd = cli();
    let mut texts = vec![cmd.render_long_help().to_string()];
    for name in ["classify", "decrypt", "encrypt"] {
        texts.push(
            cmd.find_subcommand_mut(name)
                .expect("subcommand")
                .render_long_help()
                .to_string(),
        );
    }
    for text in texts {
        for line in text.lines() {
            let t = line.trim_start();
            assert!(
                !(t.starts_with("--password ") || t.starts_with("--password=")),
                "a `--password <VALUE>` option must never be defined in help: {line:?}"
            );
        }
    }
}

#[test]
fn help_advertises_the_three_real_password_sources() {
    let mut cmd = cli();
    for name in ["decrypt", "encrypt"] {
        let text = cmd
            .find_subcommand_mut(name)
            .expect("subcommand")
            .render_long_help()
            .to_string();
        for flag in ["--password-env", "--password-file", "--password-stdin"] {
            assert!(text.contains(flag), "{name} help must offer {flag}");
        }
    }
}

#[test]
fn classification_json_is_valid_json_for_a_real_golden() {
    let bytes = include_bytes!("../../tests/goldens/lo-wholesome-gcm-argon2.odt");
    let c = classify(bytes).expect("golden classifies");
    let v: serde_json::Value =
        serde_json::from_str(&classification_json(&c)).expect("must be valid JSON");

    assert_eq!(v["mode"], "wholesome");
    assert_eq!(v["encrypted"], true);
    assert_eq!(v["cipher"], "AES-GCM (W3C)");
    assert_eq!(v["kdf"], "Argon2id t=3 m=65536KiB p=4");
    assert_eq!(v["key_size"], 32);
    assert_eq!(v["odf_version"], "1.4");
}

#[test]
fn classification_json_nulls_the_row_fields_when_plain() {
    let bytes = include_bytes!("../../tests/goldens/lo-unencrypted.odt");
    let c = classify(bytes).expect("golden classifies");
    let v: serde_json::Value =
        serde_json::from_str(&classification_json(&c)).expect("must be valid JSON");
    assert_eq!(v["encrypted"], false);
    assert!(v["cipher"].is_null());
    assert!(v["key_size"].is_null());
}

#[test]
fn human_output_reports_plain_as_an_answer_not_a_failure() {
    let bytes = include_bytes!("../../tests/goldens/lo-unencrypted.odt");
    let c = classify(bytes).expect("golden classifies");
    let text = classification_human(&c);
    assert!(text.contains("mode:        plain"));
    assert!(text.contains("encrypted:   no"));
    // No cipher block for a package that has none.
    assert!(!text.contains("cipher:"));
}

#[test]
fn human_output_names_the_algorithm_tuple() {
    let bytes = include_bytes!("../../tests/goldens/aoo-blowfish-pbkdf2.odt");
    let c = classify(bytes).expect("golden classifies");
    let text = classification_human(&c);
    assert!(text.contains("mode:        per-entry"));
    assert!(text.contains("Blowfish-CFB"));
    assert!(text.contains("PBKDF2 iterations="));
}

#[test]
fn host_capacity_is_not_reported_as_a_damaged_document() {
    // The whole point of `HostCannotAllocate` is that the file is fine and the
    // machine is not. Both variants reached the trailing `_ => EX_MALFORMED`
    // arm when they were added -- the third time a new variant has done that,
    // after `EncryptError::Params` -- which told the user their document was
    // malformed for a memory failure. Pin both, and pin that it is NOT 6.
    assert_eq!(
        decrypt_exit(&DecryptError::HostCannotAllocate {
            site: AllocationSite::MemberPlaintext,
            requested_bytes: 1 << 30
        }),
        EX_HOST_CAPACITY
    );
    assert_eq!(
        encrypt_exit(&EncryptError::HostCannotAllocate {
            requested_bytes: 1 << 30
        }),
        EX_HOST_CAPACITY
    );
    assert_ne!(
        decrypt_exit(&DecryptError::HostCannotAllocate {
            site: AllocationSite::MemberPlaintext,
            requested_bytes: 1 << 30
        }),
        EX_MALFORMED,
        "a host memory failure must never read as a damaged document"
    );
}

// --- exit-code canary (#40) ----------------------------------------------
//
// Exit codes are a contract: 4 means *wrong password, try again*, 5 means
// *refused, you had the wrong file* (CLAUDE.md). Nothing pinned them, so a
// change to `decrypt_exit` was a silent change to a scripted interface.
//
// These three tests are the *correctness* half of the guard. They are not the
// completeness half and cannot be, which is worth stating where someone would
// otherwise add a match here and believe the job done: `DetectError`,
// `DecryptError` and `EncryptError` are `#[non_exhaustive]`, and this binary is
// a separate crate from the library defining them, so rustc requires a `_` arm
// here exactly as it does in the mapping. Measured, not assumed -- a
// wildcard-free match in this file fails to build with E0004, "`DecryptError`
// is marked as non-exhaustive, so a wildcard `_` is necessary to match
// exhaustively".
//
// Completeness therefore lives in the library, where the attribute does not
// apply: `every_*_variant_is_accounted_for_in_the_cli_exit_map` in
// `src/classify_tests.rs`, `src/decrypt_tests.rs` and `src/encrypt_tests.rs`
// stop compiling when a variant is added. Neither half is sufficient alone.

#[test]
fn the_detect_exit_map_is_the_documented_one() {
    for (e, want) in [
        (DetectError::NotZip, EX_NOT_ODF),
        (DetectError::MissingManifest, EX_NOT_ODF),
        (DetectError::Inconsistent(String::new()), EX_REFUSED),
        (DetectError::Zip(String::new()), EX_MALFORMED),
        (DetectError::Io(std::io::Error::other("cancelled")), EX_IO),
    ] {
        assert_eq!(detect_exit(&e), want, "{e:?}");
    }
}

#[test]
fn the_decrypt_exit_map_is_the_documented_one() {
    for (e, want) in [
        // Not a constant: `Classify` delegates, so this pins the delegation
        // rather than a number that happens to agree with it today.
        (
            DecryptError::Classify(DetectError::MissingManifest),
            EX_NOT_ODF,
        ),
        (
            DecryptError::Classify(DetectError::Zip(String::new())),
            EX_MALFORMED,
        ),
        (DecryptError::WrongPassword, EX_WRONG_PASSWORD),
        (DecryptError::NotEncrypted, EX_REFUSED),
        (DecryptError::Odf12Fatal, EX_REFUSED),
        (DecryptError::UnsupportedPgp, EX_REFUSED),
        (DecryptError::EmptyPassword, EX_REFUSED),
        (
            DecryptError::BadParameters(odf_crypto::BadParameter::NoMember { row: 0 }),
            EX_MALFORMED,
        ),
        (DecryptError::Inflate(String::new()), EX_MALFORMED),
        (DecryptError::Zip(String::new()), EX_MALFORMED),
        (DecryptError::Internal(String::new()), EX_INTERNAL),
        (
            DecryptError::HostCannotAllocate {
                // Any site; the exit code is a property of the variant, not of
                // which allocation failed. `AllocationSite` is diagnostic.
                site: AllocationSite::CipherBuffer,
                requested_bytes: 1 << 40,
            },
            EX_HOST_CAPACITY,
        ),
        (DecryptError::OutputLimit { limit: 1 }, EX_REFUSED),
        (DecryptError::Io(std::io::Error::other("cancelled")), EX_IO),
    ] {
        assert_eq!(decrypt_exit(&e), want, "{e:?}");
    }
}

#[test]
fn the_encrypt_exit_map_is_the_documented_one() {
    // Built through the real constructor rather than assembled by hand, so the
    // test keeps working if `ParamsReason`'s shape changes and stops working if
    // `new` stops rejecting this tuple.
    let params = Argon2Params::new(0, 65536, 1)
        .expect_err("t = 0 is below ARGON2_MIN_T_COST and must be refused");

    for (e, want) in [
        (EncryptError::Classify(DetectError::NotZip), EX_NOT_ODF),
        (EncryptError::AlreadyEncrypted, EX_REFUSED),
        // Same code as AlreadyEncrypted, deliberately: both mean "wrong file,
        // do not retry". What the split fixed is which claim is made about the
        // file, not what a script should do about it.
        (EncryptError::PartiallyEncrypted, EX_REFUSED),
        (EncryptError::Odf12Fatal, EX_REFUSED),
        (EncryptError::EmptyPassword, EX_REFUSED),
        (EncryptError::Mimetype(String::new()), EX_MALFORMED),
        (EncryptError::Deflate(String::new()), EX_MALFORMED),
        (EncryptError::Zip(String::new()), EX_MALFORMED),
        // The caller typed a bad --argon2-* value; the document is fine. This
        // is the variant that fell through the `_` arm when it was added.
        (params, EX_USAGE),
        (EncryptError::Random(String::new()), EX_INTERNAL),
        (EncryptError::Internal(String::new()), EX_INTERNAL),
        (
            EncryptError::HostCannotAllocate {
                requested_bytes: 1 << 40,
            },
            EX_HOST_CAPACITY,
        ),
        (EncryptError::Io(std::io::Error::other("cancelled")), EX_IO),
    ] {
        assert_eq!(encrypt_exit(&e), want, "{e:?}");
    }
}

#[test]
fn the_reencrypt_exit_map_is_the_documented_one() {
    for (e, want) in [
        // Each side delegates to its own table: a wrong old password is 4,
        // an empty new one is 5, as from `decrypt` and `encrypt`.
        (
            ReencryptError::Decrypt(DecryptError::WrongPassword),
            EX_WRONG_PASSWORD,
        ),
        (
            ReencryptError::Encrypt(EncryptError::EmptyPassword),
            EX_REFUSED,
        ),
        (ReencryptError::PartiallyEncrypted, EX_REFUSED),
        (ReencryptError::UnexpectedStreams, EX_REFUSED),
        (
            ReencryptError::Io(std::io::Error::other("cancelled")),
            EX_IO,
        ),
    ] {
        assert_eq!(reencrypt_exit(&e), want, "{e:?}");
    }
}