ferrocrypt 0.3.0

Recipient-oriented file and directory encryption: passphrase (Argon2id) and X25519 public-key recipients, XChaCha20-Poly1305 STREAM payloads, HKDF-SHA3-256 / HMAC-SHA3-256 key derivation and authentication.
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
//! Replays the committed `testvectors/suite/` edge-case corpus.
//!
//! Reads `testvectors/suite/manifest.tsv` and runs every row through the
//! public API exactly as an independent implementation would: decrypt
//! each `.fcr` with the listed credential, read each `public.key`, or
//! structurally validate each `private.key`, and require the listed outcome.
//! Successful `decrypt` rows must reproduce the content of `plaintext.txt`
//! byte-for-byte under the name the fixture's archive stores;
//! successful key-file rows must parse or validate without error. `error`
//! rows must fail with both the listed typed error class and the exact
//! user-facing message.
//!
//! The corpus is generated by the ignored `suite_vector_gen` unit test
//! in the library crate, which needs crate internals to craft the
//! must-reject bytes. This test deliberately uses only public API and
//! only committed files, so a failure means either the reader's
//! behaviour drifted or the committed corpus no longer tells the truth.

use std::fs;
use std::path::{Path, PathBuf};

use ferrocrypt::Passphrase;
use ferrocrypt::{
    CryptoError, Decryptor, FormatDefect, InvalidKdfParams, PrivateKey, PublicKey,
    UnsupportedVersion, validate_private_key_file,
};

const TEST_WORKSPACE: &str = "tests/workspace_testvector_suite";

fn suite_dir() -> PathBuf {
    Path::new(env!("CARGO_MANIFEST_DIR")).join("testvectors/suite")
}

#[ctor::dtor]
fn cleanup() {
    ferrocrypt_test_support::remove_per_process_workspace(TEST_WORKSPACE);
}

/// One parsed `manifest.tsv` row.
struct Row {
    file: String,
    action: String,
    credential: String,
    expect: String,
    error_class: String,
    error_message: String,
}

fn parse_manifest(suite: &Path) -> Vec<Row> {
    let text = fs::read_to_string(suite.join("manifest.tsv")).expect("read manifest.tsv");
    text.lines()
        .filter(|line| !line.is_empty() && !line.starts_with('#'))
        .map(|line| {
            let fields: Vec<&str> = line.split('\t').collect();
            assert_eq!(fields.len(), 6, "manifest row must have 6 fields: {line}");
            Row {
                file: fields[0].to_string(),
                action: fields[1].to_string(),
                credential: fields[2].to_string(),
                expect: fields[3].to_string(),
                error_class: fields[4].to_string(),
                error_message: fields[5].to_string(),
            }
        })
        .collect()
}

/// Checks that `e` is the typed variant the manifest's `error_class`
/// column names. The class labels are the manifest's stable vocabulary;
/// extend this mapping when the corpus grows a new class.
fn error_matches(class: &str, e: &CryptoError) -> bool {
    match class {
        "InvalidFormat(BadMagic)" => {
            matches!(e, CryptoError::InvalidFormat(FormatDefect::BadMagic))
        }
        "InvalidFormat(WrongKind)" => {
            matches!(
                e,
                CryptoError::InvalidFormat(FormatDefect::WrongKind { .. })
            )
        }
        "InvalidFormat(MalformedHeader)" => {
            matches!(e, CryptoError::InvalidFormat(FormatDefect::MalformedHeader))
        }
        "InvalidFormat(MalformedPayloadStream)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::MalformedPayloadStream)
        ),
        "InvalidFormat(OversizedHeader)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::OversizedHeader { .. })
        ),
        "InvalidFormat(Truncated)" => {
            matches!(e, CryptoError::InvalidFormat(FormatDefect::Truncated))
        }
        "InvalidFormat(MalformedTlv)" => {
            matches!(e, CryptoError::InvalidFormat(FormatDefect::MalformedTlv))
        }
        "InvalidFormat(UnknownCriticalTag)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::UnknownCriticalTag { .. })
        ),
        "InvalidFormat(MalformedRecipientEntry)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)
        ),
        "InvalidFormat(RecipientFlagsReserved)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::RecipientFlagsReserved)
        ),
        "InvalidFormat(MalformedPublicKey)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::MalformedPublicKey)
        ),
        "InvalidFormat(NotAKeyFile)" => {
            matches!(e, CryptoError::InvalidFormat(FormatDefect::NotAKeyFile))
        }
        "InvalidFormat(WrongKeyFileType)" => {
            matches!(
                e,
                CryptoError::InvalidFormat(FormatDefect::WrongKeyFileType)
            )
        }
        "InvalidFormat(MalformedPrivateKey)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::MalformedPrivateKey)
        ),
        "UnsupportedVersion(NewerKey)" => matches!(
            e,
            CryptoError::UnsupportedVersion(UnsupportedVersion::NewerKey { .. })
        ),
        "UnsupportedVersion(NewerPublicKey)" => matches!(
            e,
            CryptoError::UnsupportedVersion(UnsupportedVersion::NewerPublicKey { .. })
        ),
        "KeyFileUnlockFailed" => matches!(e, CryptoError::KeyFileUnlockFailed),
        "MalformedArchive" => matches!(e, CryptoError::MalformedArchive { .. }),
        "UnsafeArchivePath" => matches!(e, CryptoError::UnsafeArchivePath { .. }),
        "InvalidFormat(UnsupportedArchiveVersion)" => matches!(
            e,
            CryptoError::InvalidFormat(FormatDefect::UnsupportedArchiveVersion { .. })
        ),
        "UnsupportedVersion(NewerFile)" => matches!(
            e,
            CryptoError::UnsupportedVersion(UnsupportedVersion::NewerFile { .. })
        ),
        "InvalidKdfParams(MemoryCost)" => matches!(
            e,
            CryptoError::InvalidKdfParams(InvalidKdfParams::MemoryCost(_))
        ),
        "InvalidKdfParams(Parallelism)" => matches!(
            e,
            CryptoError::InvalidKdfParams(InvalidKdfParams::Parallelism(_))
        ),
        "InvalidKdfParams(TimeCost)" => matches!(
            e,
            CryptoError::InvalidKdfParams(InvalidKdfParams::TimeCost(_))
        ),
        "KdfResourceCapExceeded" => matches!(e, CryptoError::KdfResourceCapExceeded { .. }),
        "PayloadTruncated" => matches!(e, CryptoError::PayloadTruncated),
        "PayloadTampered" => matches!(e, CryptoError::PayloadTampered),
        "HeaderTampered" => matches!(e, CryptoError::HeaderTampered),
        "HeaderMacFailedAfterUnwrap(x25519)" => matches!(
            e,
            CryptoError::HeaderMacFailedAfterUnwrap { type_name } if type_name == "x25519"
        ),
        "RecipientUnwrapFailed(argon2id)" => matches!(
            e,
            CryptoError::RecipientUnwrapFailed { type_name } if type_name == "argon2id"
        ),
        "RecipientUnwrapFailed(x25519)" => matches!(
            e,
            CryptoError::RecipientUnwrapFailed { type_name } if type_name == "x25519"
        ),
        // The unknown recipient's name is a corpus choice, so read it
        // from the manifest rather than repeating it here.
        _ if class.starts_with("UnknownCriticalRecipient(") && class.ends_with(')') => {
            let expected = &class["UnknownCriticalRecipient(".len()..class.len() - 1];
            matches!(e, CryptoError::UnknownCriticalRecipient { type_name } if type_name == expected)
        }
        "NoSupportedRecipient" => matches!(e, CryptoError::NoSupportedRecipient),
        "IncompatibleRecipients(argon2id)" => matches!(
            e,
            CryptoError::IncompatibleRecipients { type_name, .. } if type_name == "argon2id"
        ),
        "InvalidInput" => matches!(e, CryptoError::InvalidInput(_)),
        other => panic!("manifest names an error class this test does not map: {other}"),
    }
}

/// Runs one manifest row's attempt. `Ok(())` means the action fully
/// succeeded (for `decrypt`, the output landed in `out`).
fn attempt(suite: &Path, row: &Row, out: &Path) -> Result<(), CryptoError> {
    match row.action.as_str() {
        "decrypt" => {
            let decryptor = Decryptor::open(suite.join(&row.file))?;
            match decryptor {
                Decryptor::Passphrase(d) => {
                    let literal = row
                        .credential
                        .strip_prefix("passphrase:")
                        .unwrap_or_else(|| {
                            panic!(
                                "{}: passphrase file needs a passphrase credential, got `{}`",
                                row.file, row.credential
                            )
                        });
                    d.decrypt(Passphrase::new(literal), out, |_| {})?;
                }
                Decryptor::PrivateKey(d) => {
                    let rest = row
                        .credential
                        .strip_prefix("private-key:")
                        .unwrap_or_else(|| {
                            panic!(
                                "{}: recipient file needs a private-key credential, got `{}`",
                                row.file, row.credential
                            )
                        });
                    let (key_path, unlock) = rest
                        .split_once(",unlock=")
                        .expect("private-key credential carries an unlock passphrase");
                    d.decrypt(
                        PrivateKey::from_key_file(suite.join(key_path), Passphrase::new(unlock)),
                        out,
                        |_| {},
                    )?;
                }
                other => panic!("{}: unexpected decryptor variant {other:?}", row.file),
            }
            Ok(())
        }
        "read-public-key" => PublicKey::from_key_file(suite.join(&row.file)).map(|_| ()),
        "validate-private-key" => validate_private_key_file(suite.join(&row.file)),
        other => panic!("{}: unknown manifest action `{other}`", row.file),
    }
}

/// Returns the one entry a successful decrypt left in `out`. The name
/// is whatever the fixture's archive stored — `plaintext.txt` for most
/// rows, a name carrying an accepted direction mark for the §9.6 case —
/// so the harness locates the output rather than assuming its name.
fn single_output_entry(out: &Path) -> Result<PathBuf, String> {
    let mut entries: Vec<PathBuf> = fs::read_dir(out)
        .map_err(|e| format!("its output directory cannot be listed: {e}"))?
        .map(|entry| entry.map(|entry| entry.path()))
        .collect::<Result<_, _>>()
        .map_err(|e| format!("its output directory cannot be listed: {e}"))?;
    match entries.len() {
        1 => Ok(entries.remove(0)),
        0 => Err("its output directory is empty".to_owned()),
        n => Err(format!(
            "its output directory holds {n} entries, expected 1"
        )),
    }
}

/// Replays every manifest row and collects mismatches, so one run
/// reports every divergence instead of stopping at the first.
#[test]
fn suite_manifest_holds() {
    let suite = suite_dir();
    let rows = parse_manifest(&suite);
    assert!(!rows.is_empty(), "manifest.tsv has no rows");
    let expected_plaintext = fs::read(suite.join("plaintext.txt")).expect("read plaintext.txt");

    let mut failures = Vec::new();
    for (index, row) in rows.iter().enumerate() {
        // Per-process subtree, so a concurrent `cargo test` invocation
        // of this binary cannot delete files this run is using.
        let out = ferrocrypt_test_support::per_process_workspace(TEST_WORKSPACE)
            .join(format!("row-{index}"));
        if out.exists() {
            fs::remove_dir_all(&out).expect("clean row output dir");
        }
        fs::create_dir_all(&out).expect("create row output dir");

        let outcome = attempt(&suite, row, &out);
        match (row.expect.as_str(), outcome) {
            ("ok", Ok(())) => match row.action.as_str() {
                "decrypt" => match single_output_entry(&out) {
                    Ok(path) => match fs::read(&path) {
                        Ok(bytes) if bytes == expected_plaintext => {}
                        Ok(_) => {
                            failures.push(format!("{}: decrypted plaintext differs", row.file));
                        }
                        Err(e) => failures.push(format!(
                            "{}: decrypt succeeded but its output cannot be read: {e}",
                            row.file
                        )),
                    },
                    Err(detail) => {
                        failures.push(format!("{}: decrypt succeeded but {detail}", row.file));
                    }
                },
                "read-public-key" | "validate-private-key" => {}
                other => panic!("{}: unknown manifest action `{other}`", row.file),
            },
            ("ok", Err(e)) => {
                failures.push(format!("{}: expected success, got `{e}` ({e:?})", row.file));
            }
            ("error", Err(e)) => {
                if !error_matches(&row.error_class, &e) {
                    failures.push(format!(
                        "{}: expected class {}, got {e:?}",
                        row.file, row.error_class
                    ));
                }
                if e.to_string() != row.error_message {
                    failures.push(format!(
                        "{}: expected message `{}`, got `{e}`",
                        row.file, row.error_message
                    ));
                }
            }
            ("error", Ok(())) => {
                failures.push(format!(
                    "{}: expected {} to fail, but it succeeded",
                    row.file, row.error_class
                ));
            }
            (other, _) => panic!("{}: unknown expect value `{other}`", row.file),
        }
    }

    assert!(
        failures.is_empty(),
        "suite corpus diverged:\n{}",
        failures.join("\n")
    );
}

/// FORMAT.md §3.7 step 8: a native recipient body of the wrong length
/// is rejected by [`Decryptor::open`] itself. No credential can be
/// supplied at that point, so the expensive private-key unlock (and its
/// `UnlockingPrivateKey` progress event) is unreachable for these
/// fixtures — the regression this test pins.
#[test]
fn invalid_length_fixtures_reject_at_open_before_any_credential() {
    let suite = suite_dir();
    for fixture in [
        "cases/x25519-invalid-length.fcr",
        "cases/x25519-invalid-length-second-slot.fcr",
        "cases/argon2id-invalid-length.fcr",
    ] {
        match Decryptor::open(suite.join(fixture)) {
            Err(CryptoError::InvalidFormat(FormatDefect::MalformedRecipientEntry)) => {}
            other => panic!("{fixture}: expected MalformedRecipientEntry at open, got {other:?}"),
        }
    }
}

/// FORMAT.md §4.1 makes `kdf_params` outside the §2.2 bounds a reader
/// rejection, and §3.7 places it in the same step-8 preflight as body
/// length. These fixtures must therefore reject at [`Decryptor::open`]
/// too, rather than being classified as passphrase files and only
/// failing once a passphrase has been collected.
#[test]
fn invalid_kdf_fixtures_reject_at_open_before_any_credential() {
    let suite = suite_dir();
    for fixture in [
        "cases/kdf-mem-over-max.fcr",
        "cases/kdf-lanes-zero.fcr",
        "cases/kdf-time-over-max.fcr",
    ] {
        match Decryptor::open(suite.join(fixture)) {
            Err(CryptoError::InvalidKdfParams(_)) => {}
            other => panic!("{fixture}: expected InvalidKdfParams at open, got {other:?}"),
        }
    }
}

/// Every committed case or key file must be exercised by at least one
/// manifest row, either as the row's action target or as its private-key
/// credential. A fixture without a row is dead weight, and a row that
/// references a missing fixture is a broken promise.
#[test]
fn manifest_covers_every_fixture_file() {
    let suite = suite_dir();
    let rows = parse_manifest(&suite);

    let mut referenced: std::collections::HashSet<String> =
        rows.iter().map(|row| row.file.clone()).collect();
    for row in &rows {
        if let Some(rest) = row.credential.strip_prefix("private-key:") {
            let (key_path, _) = rest
                .split_once(",unlock=")
                .expect("private-key credential carries an unlock passphrase");
            referenced.insert(key_path.to_string());
        }
    }

    for name in &referenced {
        assert!(
            suite.join(name).is_file(),
            "manifest references a missing fixture: {name}"
        );
    }

    for directory in ["cases", "keys"] {
        for entry in fs::read_dir(suite.join(directory)).expect("read fixture directory") {
            let entry = entry.expect("fixture directory entry");
            let file_name = entry.file_name();
            let name = file_name.to_string_lossy();
            // Skip filesystem litter such as .DS_Store; it is not corpus content.
            if name.starts_with('.') {
                continue;
            }
            assert!(
                entry.file_type().expect("fixture file type").is_file(),
                "fixture directory contains a non-file entry: {}",
                entry.path().display()
            );
            let name = format!("{directory}/{name}");
            assert!(
                referenced.contains(&name),
                "committed fixture file has no manifest row: {name}"
            );
        }
    }
}