ferrocrypt/lib.rs
1//! # ferrocrypt
2//!
3//! Authenticated encryption of files and directories.
4//!
5//! FerroCrypt writes `.fcr` files using one recipient-oriented container:
6//! one random per-file key, one streamed authenticated payload, and one or more
7//! typed recipient entries that independently wrap the same file key. The public
8//! API exposes this through [`Encryptor`] and [`Decryptor`] rather than through
9//! low-level cryptographic building blocks.
10//!
11//! ## Design goals
12//!
13//! - **Recipient-oriented encryption**: passphrases and public keys are native
14//! recipient schemes over the same `.fcr` container.
15//! - **Path-based file workflows**: archiving, streaming encryption, staging,
16//! and output naming are handled by the library.
17//! - **Typed routing**: [`Decryptor::open`] inspects the recipient list and
18//! returns a passphrase or private-key decryptor variant.
19//! - **Typed diagnostics**: operations return [`CryptoError`] values with
20//! structured format, KDF, recipient, authentication, and I/O failures.
21//!
22//! ## Quick start (passphrase recipient)
23//!
24//! These examples assume the input paths exist and the output names are unused.
25//!
26//! ```rust,no_run
27//! use ferrocrypt::{Decryptor, Encryptor, CryptoError, Passphrase};
28//!
29//! # fn run() -> Result<(), CryptoError> {
30//! std::fs::create_dir_all("./out")?;
31//! std::fs::create_dir_all("./restored")?;
32//! // Encrypt
33//! let encrypted = Encryptor::with_passphrase(Passphrase::new("correct horse battery staple"))
34//! .write("./secrets", "./out", |ev| eprintln!("{ev}"))?;
35//! println!("Encrypted to {}", encrypted.output_path.display());
36//!
37//! // Decrypt — each operation consumes its own `Passphrase` value
38//! let restored = match Decryptor::open(&encrypted.output_path)? {
39//! Decryptor::Passphrase(d) => d.decrypt(
40//! Passphrase::new("correct horse battery staple"),
41//! "./restored",
42//! |ev| eprintln!("{ev}"),
43//! )?,
44//! Decryptor::PrivateKey(_) => unreachable!("we just encrypted with a passphrase"),
45//! _ => unreachable!("Decryptor is non_exhaustive; only Passphrase and PrivateKey exist today"),
46//! };
47//! println!("Decrypted to {}", restored.output_path.display());
48//! # Ok(()) }
49//! # fn main() { run().unwrap(); }
50//! ```
51//!
52//! ## Quick start (public-key recipients)
53//! ```rust,no_run
54//! use ferrocrypt::{
55//! Decryptor, Encryptor, generate_key_pair, PublicKey, PrivateKey,
56//! CryptoError, Passphrase,
57//! };
58//!
59//! # fn run() -> Result<(), CryptoError> {
60//! std::fs::create_dir_all("./out")?;
61//! std::fs::create_dir_all("./restored")?;
62//! // 1) Generate X25519 keypair
63//! let keys = generate_key_pair("./keys", Passphrase::new("my-key-pass"), |ev| eprintln!("{ev}"))?;
64//! println!("Fingerprint: {}", keys.fingerprint);
65//!
66//! // 2) Encrypt with the recipient's public key (no passphrase required)
67//! let encrypted = Encryptor::with_public_key(PublicKey::from_key_file(&keys.public_key_path)?)
68//! .write("./payload", "./out", |ev| eprintln!("{ev}"))?;
69//!
70//! // 3) Decrypt with the recipient's private key + its passphrase
71//! let restored = match Decryptor::open(&encrypted.output_path)? {
72//! Decryptor::PrivateKey(d) => d.decrypt(
73//! PrivateKey::from_key_file(&keys.private_key_path, Passphrase::new("my-key-pass")),
74//! "./restored",
75//! |ev| eprintln!("{ev}"),
76//! )?,
77//! Decryptor::Passphrase(_) => unreachable!("we just encrypted to a public key"),
78//! _ => unreachable!("Decryptor is non_exhaustive; only Passphrase and PrivateKey exist today"),
79//! };
80//! println!("Decrypted to {}", restored.output_path.display());
81//! # Ok(()) }
82//! # fn main() { run().unwrap(); }
83//! ```
84//!
85//! ## Choosing a recipient path
86//!
87//! - **Passphrase recipient**: use [`Encryptor::with_passphrase`] when the
88//! same passphrase should encrypt and decrypt the file. The resulting `.fcr`
89//! contains exactly one native `argon2id` recipient.
90//! - **Public-key recipient**: use [`Encryptor::with_public_key`] or
91//! [`Encryptor::with_public_keys`] when the sender should encrypt to one or
92//! more public recipient keys. Decryption requires a matching [`PrivateKey`]
93//! file and that key file's passphrase. This does not authenticate the sender.
94//!
95//! ## Format compatibility
96//!
97//! FerroCrypt stores four independent version bytes: `.fcr` outer-container
98//! version `0x01`, FCA archive version `0x01`, public-key encoding version
99//! `0x01`, and private-key encoding version `0x01`. The compatibility
100//! guarantee starts with the first stable `0.3.0` release. The `0.3.0`
101//! pre-release series (`-alpha.N`, `-beta.N`, `-rc.N`) is outside it: files
102//! written by a pre-release or by an untagged build of `main` carry no
103//! cross-version guarantee and may fail to decrypt under a later release.
104//!
105//! Stable `0.3.0` establishes the `0.3.0` compatibility baseline
106//! (`FORMAT.md` §11.4): artifacts that use only the four stored versions
107//! above stay readable under every later release. A future release may
108//! introduce a new version in any one domain; that adds support without
109//! removing baseline read support.
110//!
111//! Older pre-`0.3.0` files and key pairs use a different format family and, for
112//! historical hybrid encryption, a different key-agreement stack. To migrate
113//! older data, decrypt it with the release that created it, then re-encrypt it
114//! with the current release.
115//!
116//! ## API stability
117//!
118//! The on-disk format is versioned independently from the crate; see
119//! *Format compatibility* above for its stability guarantee.
120//! The public Rust API ([`Encryptor`], [`Decryptor`], [`PublicKey`],
121//! [`PrivateKey`], the error types) is pre-1.0; it may change in minor releases
122//! (0.x → 0.y), while patch releases (0.x.y → 0.x.z) preserve it. See the
123//! repository [`CHANGELOG.md`](https://github.com/alexylon/ferrocrypt/blob/main/CHANGELOG.md)
124//! for release notes.
125//!
126//! ## Security notes
127//!
128//! - Encryption and key generation require a secure OS random-number source.
129//! - Sender authentication is out of scope; public-key encryption identifies who
130//! can decrypt, not who encrypted.
131//! - A successful decrypt requires header and payload authentication. Wrong
132//! credentials or corrupted ciphertext return [`CryptoError`]; authenticated
133//! partial plaintext may already have been staged when a later check fails.
134//! - Passphrase and key-pair writing reject Argon2id memory below a fixed
135//! 19 MiB floor with [`CryptoError::KdfBelowWriteFloor`]. This prevents
136//! accidentally choosing a lower memory cost; it does not make a weak
137//! passphrase strong. The floor applies only when writing; readers accept lower
138//! memory costs subject to structural validation and their [`KdfLimit`].
139//! - FerroCrypt authenticates each file as written, but it does not detect
140//! replay or rollback to an older valid `.fcr`; use external versioning or a
141//! freshness check if that matters.
142//! - FerroCrypt encrypts file contents and, for directory inputs, internal
143//! names, tree structure, and per-file sizes. It does not hide the total
144//! ciphertext length (an approximate plaintext-size signal), recipient count,
145//! or that the file is a FerroCrypt `.fcr` container.
146//! - Choose output directories and path ancestors that untrusted processes
147//! cannot modify during an operation. Existing output entries are refused;
148//! an error after commit can still leave complete output on disk.
149//! - Decryption stages authenticated plaintext under an `.incomplete` name.
150//! See [`IncompleteOutputPolicy`] for cleanup, retention, and interruption
151//! behavior. Do not consume staged output as a successfully decrypted file.
152//! - Encryption is not a filesystem snapshot. Prevent concurrent source
153//! changes or use a snapshot when a point-in-time copy is required.
154//! - Unattended services must configure resource limits and bound concurrent
155//! operations. The default Argon2id memory budget is 1 GiB per derivation;
156//! see [`KdfLimit`]. These APIs perform blocking filesystem and cryptographic
157//! work; asynchronous applications should run them on a blocking worker.
158//! - Public-key checksums do not establish ownership. Verify the recipient's
159//! fingerprint through a trusted channel before encrypting.
160//! - This crate is **not** third-party audited and is not advertised as
161//! compliance-certified.
162//!
163//! ## Error handling
164//!
165//! Every fallible operation returns `Result<T, CryptoError>`. See
166//! [`CryptoError`] for variant meanings and remediation hints.
167//!
168//! ## License
169//! Licensed under GPL-3.0-only. See the LICENSE file in the repository.
170
171#![forbid(unsafe_code)]
172#![warn(missing_docs)]
173#![warn(rustdoc::broken_intra_doc_links)]
174#![warn(rustdoc::bare_urls)]
175
176use std::path::PathBuf;
177
178/// The crate version from `Cargo.toml`, captured at compile time.
179pub const VERSION: &str = env!("CARGO_PKG_VERSION");
180
181pub use crate::api::{
182 Decryptor, Encryptor, KeyPairGenerator, PassphraseDecryptor, PrivateKeyDecryptor,
183 default_encrypted_filename, escape_path_for_display, generate_key_pair, probe_recipient_mode,
184 probe_recipient_mode_with_limits, validate_private_key_file, validate_public_key_file,
185};
186pub use crate::archive::{ArchiveLimits, IncompleteOutputPolicy};
187pub use crate::container::HeaderReadLimits;
188pub use crate::crypto::kdf::{ARGON2_SALT_SIZE, KDF_PARAMS_SIZE, KdfLimit, KdfParams};
189pub use crate::error::{CryptoError, FormatDefect, InvalidKdfParams, UnsupportedVersion};
190pub use crate::format::{ENCRYPTED_EXTENSION, FCR_FILE_V1_VERSION, FCR_FILE_VERSION, MAGIC};
191pub use crate::key::files::{PRIVATE_KEY_FILENAME, PUBLIC_KEY_FILENAME};
192pub use crate::key::limits::KeyReadLimits;
193pub use crate::key::private::{PRIVATE_KEY_V1_VERSION, PRIVATE_KEY_VERSION};
194pub use crate::key::public::{PUBLIC_KEY_V1_VERSION, PUBLIC_KEY_VERSION};
195pub use crate::passphrase::Passphrase;
196pub use crate::recipient::policy::MixingPolicy;
197
198/// Result of a cheap structural probe of an `.fcr` file's recipient list.
199///
200/// **Not a security claim.** [`probe_recipient_mode`] performs no KDF, no
201/// private-key operation, no credential prompt, no header-MAC verification,
202/// and no payload decryption. A positive result is not evidence that the file
203/// is authentic, decryptable, untampered, or well-formed beyond the structural
204/// shape required to classify it. Use only for UI / routing hints.
205///
206/// For an authenticated mode value — produced only after a recipient unwraps
207/// and the header MAC verifies — see [`AuthenticatedRecipientMode`] on
208/// [`DecryptOutcome`].
209///
210/// This enum remains `Copy`: its variants are categorical and carry no data,
211/// including any added in future releases.
212#[derive(Debug, Clone, Copy, PartialEq, Eq)]
213#[non_exhaustive]
214pub enum UnauthenticatedRecipientMode {
215 /// File contains exactly one native `argon2id` recipient and is decrypted
216 /// with a passphrase.
217 Passphrase,
218 /// File contains one or more native `x25519` public-key recipients and is
219 /// decrypted with a matching [`PrivateKey`].
220 PublicKey,
221}
222
223impl std::fmt::Display for UnauthenticatedRecipientMode {
224 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
225 let label = match self {
226 Self::Passphrase => "passphrase",
227 Self::PublicKey => "public-key",
228 };
229 f.write_str(label)
230 }
231}
232
233impl UnauthenticatedRecipientMode {
234 /// Name of the credential the caller must supply to decrypt a file in
235 /// this mode. Used by the `DecryptorModeMismatch` error wording so the
236 /// message tells the caller which credential to switch to instead of
237 /// leaving them to infer it from the recipient kind.
238 pub(crate) const fn credential_name(self) -> &'static str {
239 match self {
240 Self::Passphrase => "a passphrase",
241 Self::PublicKey => "a private key",
242 }
243 }
244}
245
246/// Recipient mode returned after successful authenticated decryption.
247///
248/// Available through [`DecryptOutcome::recipient_mode`]. Only the library can
249/// construct this value; a structural [`UnauthenticatedRecipientMode`] cannot
250/// be converted into one. Use [`Self::kind`] to match on the recipient kind.
251/// This value records a successful operation, not the current contents of a
252/// path or the sender's identity.
253///
254/// This sealed wrapper remains `Copy` because it holds only the categorical
255/// recipient kind.
256#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257pub struct AuthenticatedRecipientMode {
258 kind: AuthenticatedRecipientModeKind,
259}
260
261/// Recipient kind exposed by [`AuthenticatedRecipientMode::kind`].
262///
263/// This enum alone is not evidence of authentication. Match with a wildcard
264/// arm to allow for additional recipient kinds in future releases.
265///
266/// This enum remains `Copy`: its variants are categorical and carry no data,
267/// including any added in future releases.
268#[derive(Debug, Clone, Copy, PartialEq, Eq)]
269#[non_exhaustive]
270pub enum AuthenticatedRecipientModeKind {
271 /// File was sealed with a passphrase recipient (`argon2id`).
272 Passphrase,
273 /// File was sealed to one or more public-key recipients (`x25519`).
274 PublicKey,
275}
276
277impl AuthenticatedRecipientMode {
278 pub(crate) const fn passphrase() -> Self {
279 Self {
280 kind: AuthenticatedRecipientModeKind::Passphrase,
281 }
282 }
283
284 pub(crate) const fn public_key() -> Self {
285 Self {
286 kind: AuthenticatedRecipientModeKind::PublicKey,
287 }
288 }
289
290 /// Returns the recipient kind for pattern matching.
291 pub const fn kind(&self) -> AuthenticatedRecipientModeKind {
292 self.kind
293 }
294
295 /// `true` if the file authenticated as a passphrase recipient.
296 pub const fn is_passphrase(&self) -> bool {
297 matches!(self.kind, AuthenticatedRecipientModeKind::Passphrase)
298 }
299
300 /// `true` if the file authenticated as a public-key recipient.
301 pub const fn is_public_key(&self) -> bool {
302 matches!(self.kind, AuthenticatedRecipientModeKind::PublicKey)
303 }
304}
305
306impl std::fmt::Display for AuthenticatedRecipientModeKind {
307 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
308 let label = match self {
309 Self::Passphrase => "passphrase",
310 Self::PublicKey => "public-key",
311 };
312 f.write_str(label)
313 }
314}
315
316impl std::fmt::Display for AuthenticatedRecipientMode {
317 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
318 self.kind.fmt(f)
319 }
320}
321
322/// Progress notification for encryption, decryption, or key generation.
323///
324/// Operations invoke the callback synchronously on the calling thread when
325/// they enter a phase. A notification does not guarantee that the phase or
326/// operation will succeed. Keep callbacks brief and avoid panicking; panics
327/// propagate to the caller.
328///
329/// [`std::fmt::Display`] provides user-facing text. Match on variants for
330/// localization or other custom presentation, including a wildcard arm for
331/// future variants. Most events report the phase an operation enters;
332/// [`Self::BytesProcessed`] reports how far the payload phase has come.
333///
334/// This enum deliberately does not implement `Copy`: future variants may
335/// carry owned data such as entry paths. Payloads remain `Eq`-comparable;
336/// progress quantities use integers rather than floating-point values.
337#[derive(Debug, Clone, PartialEq, Eq)]
338#[non_exhaustive]
339pub enum ProgressEvent {
340 /// Argon2id is about to run to derive the passphrase wrap key for
341 /// an `argon2id` recipient. Emitted at the work boundary inside the
342 /// recipient module — after structural validation and resource-cap
343 /// checks, immediately before the KDF call. Fires zero times for a
344 /// pure public-key (X25519) `.fcr` and zero times when a malformed
345 /// `.fcr` is rejected before any KDF runs. May block for multiple
346 /// seconds.
347 DerivingPassphraseWrapKey,
348 /// Argon2id is about to run to unlock a `private.key` file. Emitted
349 /// at the work boundary inside the key-file reader — after structural
350 /// validation and resource-cap checks, immediately before the KDF
351 /// call. Fires zero times when the `private.key` is malformed and
352 /// rejected before any KDF runs. May block for multiple seconds.
353 UnlockingPrivateKey,
354 /// Payload encryption is about to begin. Emitted once if this phase is reached.
355 Encrypting,
356 /// Payload decryption is about to begin, after header authentication.
357 /// Emitted once if this phase is reached.
358 Decrypting,
359 /// Generating an X25519 key pair. Covers the entire generation flow,
360 /// including the Argon2id-driven sealing of `private.key`. The library
361 /// does not emit a nested [`Self::DerivingPassphraseWrapKey`] inside
362 /// keygen; this event already signals the long pause.
363 GeneratingKeyPair,
364 /// How many bytes of the encrypted `.fcr` file the payload phase has
365 /// handled. When encrypting, `done` counts the bytes written and `total`
366 /// is the size the finished file will have; when decrypting, `done`
367 /// counts the bytes read and `total` is the file's size when the payload
368 /// phase began, so the first `done` is the length of everything before
369 /// the payload, which was read earlier.
370 ///
371 /// Emitted after [`Self::Encrypting`] or [`Self::Decrypting`]: once when
372 /// the payload phase begins, then each time `done` reaches a further
373 /// whole percent of `total`, so one operation emits at most 101. Within
374 /// one operation every event carries the same nonzero `total`, and
375 /// `done` never decreases and never exceeds it. An operation whose
376 /// payload is handled to the end emits `done == total` last. The final
377 /// durability flush and commit still follow that event, and the
378 /// operation can still fail. A decryption that cannot read its input's
379 /// size emits no `BytesProcessed` events.
380 #[non_exhaustive]
381 BytesProcessed {
382 /// Bytes of the `.fcr` file handled so far.
383 done: u64,
384 /// Bytes of the `.fcr` file the operation handles in all.
385 total: u64,
386 },
387}
388
389impl std::fmt::Display for ProgressEvent {
390 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
391 match self {
392 Self::DerivingPassphraseWrapKey => f.write_str("Deriving passphrase key\u{2026}"),
393 Self::UnlockingPrivateKey => f.write_str("Unlocking private key\u{2026}"),
394 Self::Encrypting => f.write_str("Encrypting\u{2026}"),
395 Self::Decrypting => f.write_str("Decrypting\u{2026}"),
396 Self::GeneratingKeyPair => f.write_str("Generating key pair\u{2026}"),
397 Self::BytesProcessed { done, total } => {
398 write!(f, "{}%", progress::percent(*done, *total))
399 }
400 }
401 }
402}
403
404pub use crate::key::private::PrivateKey;
405pub use crate::key::public::PublicKey;
406
407/// Successful outcome of an [`Encryptor::write`] call.
408///
409/// Fields added in future releases remain `Eq`-comparable; quantities use
410/// integers rather than floating-point values.
411#[derive(Debug, Clone, PartialEq, Eq)]
412#[non_exhaustive]
413pub struct EncryptOutcome {
414 /// Path of the resulting `.fcr` file.
415 pub output_path: PathBuf,
416}
417
418/// Successful outcome of [`PassphraseDecryptor::decrypt`] or
419/// [`PrivateKeyDecryptor::decrypt`].
420///
421/// Fields added in future releases remain `Eq`-comparable; quantities use
422/// integers rather than floating-point values.
423#[derive(Debug, Clone, PartialEq, Eq)]
424#[non_exhaustive]
425pub struct DecryptOutcome {
426 /// Path to the extracted file or directory.
427 pub output_path: PathBuf,
428 /// Recipient mode established by the authenticated decrypt: recipient
429 /// unwrap plus header MAC verification. This value is unforgeable by
430 /// callers; only the decrypt path can construct it. Distinct from the
431 /// cheap pre-authentication [`UnauthenticatedRecipientMode`] returned by
432 /// [`probe_recipient_mode`].
433 pub recipient_mode: AuthenticatedRecipientMode,
434}
435
436/// Successful outcome of [`generate_key_pair`] or
437/// [`KeyPairGenerator::write`].
438///
439/// Fields added in future releases remain `Eq`-comparable; quantities use
440/// integers rather than floating-point values.
441#[derive(Debug, Clone, PartialEq, Eq)]
442#[non_exhaustive]
443pub struct KeyGenOutcome {
444 /// Path to the generated private key file.
445 pub private_key_path: PathBuf,
446 /// Path to the generated public key file.
447 pub public_key_path: PathBuf,
448 /// Canonical `fcr1…` Bech32 recipient string to share with senders.
449 /// Derived from the generated key material, as [`Self::fingerprint`] is,
450 /// without re-reading the public key file.
451 pub recipient_string: String,
452 /// SHA3-256 fingerprint of the public key (64 lowercase hexadecimal characters).
453 pub fingerprint: String,
454}
455
456mod api;
457mod archive;
458mod container;
459mod crypto;
460mod error;
461mod format;
462mod fs;
463mod key;
464mod passphrase;
465mod progress;
466mod protocol;
467mod recipient;
468
469#[cfg(feature = "unstable-fuzzing")]
470#[doc(hidden)]
471pub mod fuzz_exports;
472
473#[cfg(test)]
474mod suite_vector_gen;
475
476#[cfg(test)]
477mod wire_vector_gen;
478
479#[cfg(test)]
480mod wire_check_order;
481
482/// Decodes a Bech32 recipient string (`fcr1…`) into raw X25519 public-key
483/// material.
484///
485/// Validates HRP, BIP 173 checksum, internal SHA3-256 checksum,
486/// payload structural fields, type-name grammar, the
487/// [`KeyReadLimits::RECIPIENT_STRING_CHARS_DEFAULT`] recipient-string
488/// cap, and the X25519 payload constraints:
489/// `type_name == "x25519"` and exactly 32 bytes of non-zero,
490/// canonically encoded key material (`FORMAT.md` §2.4 / §7).
491///
492/// This is the low-level primitive; most callers should prefer
493/// [`PublicKey::from_recipient_string`] or
494/// `"fcr1…".parse::<PublicKey>()`, which wrap this function and yield
495/// a typed [`PublicKey`].
496///
497/// # Errors
498///
499/// Returns [`CryptoError::InvalidFormat`] with
500/// [`FormatDefect::MalformedPublicKey`] for non-ASCII, uppercase, invalid
501/// Bech32, or wrong-HRP strings, for malformed typed payloads and checksum
502/// mismatches, and for all-zero or non-canonical X25519 public keys; a payload
503/// type name that is not valid UTF-8 or breaks the type-name grammar reports
504/// [`FormatDefect::MalformedTypeName`] instead. Returns
505/// [`CryptoError::UnsupportedVersion`] for a recipient string from an
506/// unsupported keypair suite. Returns [`CryptoError::UnsupportedKeyType`] for a
507/// valid recipient string of a key type this build does not support. Returns
508/// [`CryptoError::RecipientStringCapExceeded`] when the input exceeds the local
509/// recipient-string cap.
510pub fn decode_x25519_recipient_string(recipient_string: &str) -> Result<[u8; 32], CryptoError> {
511 key::public::decode_x25519_recipient(recipient_string)
512}
513
514#[cfg(test)]
515mod tests {
516 use super::*;
517
518 /// Routes a `.fcr` file with a single `argon2id` recipient as
519 /// `UnauthenticatedRecipientMode::Passphrase`, mirroring the "exactly one
520 /// argon2id => Passphrase" classification rule. Builds the file
521 /// via `container::build_encrypted_header` so the test exercises
522 /// the same byte path the real encrypt would write.
523 #[test]
524 fn probe_recipient_mode_routes_argon2id_recipient_as_passphrase() {
525 let header_key =
526 crypto::keys::HeaderKey::from_bytes_for_tests([0x42u8; crypto::mac::HMAC_KEY_SIZE]);
527 let payload_key = crypto::keys::PayloadKey::from_bytes_for_tests(
528 [0u8; crypto::keys::ENCRYPTION_KEY_SIZE],
529 );
530 let stream_nonce = [0x07u8; crypto::stream::STREAM_NONCE_SIZE];
531 let entry = recipient::RecipientEntry::native(
532 recipient::policy::NativeRecipientType::Argon2id,
533 recipient::argon2id::test_body_with_valid_kdf_params(),
534 )
535 .unwrap();
536 let built = container::build_encrypted_header(
537 &[entry],
538 b"",
539 stream_nonce,
540 payload_key,
541 &header_key,
542 )
543 .unwrap();
544
545 let tmp = tempfile::NamedTempFile::new().unwrap();
546 let mut bytes = Vec::new();
547 bytes.extend_from_slice(&built.prefix_bytes);
548 bytes.extend_from_slice(&built.header_bytes);
549 bytes.extend_from_slice(&built.header_mac);
550 std::fs::write(tmp.path(), &bytes).unwrap();
551
552 assert_eq!(
553 probe_recipient_mode(tmp.path()).unwrap(),
554 Some(UnauthenticatedRecipientMode::Passphrase)
555 );
556 }
557
558 /// Routes a `.fcr` file with one `x25519` recipient as
559 /// `UnauthenticatedRecipientMode::PublicKey`.
560 #[test]
561 fn probe_recipient_mode_routes_x25519_recipient_as_public_key() {
562 let header_key =
563 crypto::keys::HeaderKey::from_bytes_for_tests([0x42u8; crypto::mac::HMAC_KEY_SIZE]);
564 let payload_key = crypto::keys::PayloadKey::from_bytes_for_tests(
565 [0u8; crypto::keys::ENCRYPTION_KEY_SIZE],
566 );
567 let stream_nonce = [0x07u8; crypto::stream::STREAM_NONCE_SIZE];
568 // 0x11 filler keeps the ephemeral-key field non-zero and
569 // canonical, so the body passes the structural preflight.
570 let entry = recipient::RecipientEntry::native(
571 recipient::policy::NativeRecipientType::X25519,
572 vec![0x11u8; recipient::x25519::BODY_LENGTH],
573 )
574 .unwrap();
575 let built = container::build_encrypted_header(
576 &[entry],
577 b"",
578 stream_nonce,
579 payload_key,
580 &header_key,
581 )
582 .unwrap();
583
584 let tmp = tempfile::NamedTempFile::new().unwrap();
585 let mut bytes = Vec::new();
586 bytes.extend_from_slice(&built.prefix_bytes);
587 bytes.extend_from_slice(&built.header_bytes);
588 bytes.extend_from_slice(&built.header_mac);
589 std::fs::write(tmp.path(), &bytes).unwrap();
590
591 assert_eq!(
592 probe_recipient_mode(tmp.path()).unwrap(),
593 Some(UnauthenticatedRecipientMode::PublicKey)
594 );
595 }
596
597 /// A non-FerroCrypt file (first 4 bytes are not `FCR\0`) must
598 /// route to `Ok(None)` so the encrypt path can treat it as
599 /// plaintext. The strict-detection refactor must not regress
600 /// this.
601 #[test]
602 fn probe_recipient_mode_returns_none_for_non_fcr_file() {
603 let plaintext = b"this is just a regular text file with no magic at all";
604 let tmp = tempfile::NamedTempFile::new().unwrap();
605 std::fs::write(tmp.path(), plaintext).unwrap();
606 assert_eq!(probe_recipient_mode(tmp.path()).unwrap(), None);
607 }
608
609 /// An empty file must route to `Ok(None)` (0 bytes < 4 magic
610 /// bytes; the magic test fails and detection returns None).
611 #[test]
612 fn probe_recipient_mode_returns_none_for_empty_file() {
613 let tmp = tempfile::NamedTempFile::new().unwrap();
614 std::fs::write(tmp.path(), b"").unwrap();
615 assert_eq!(probe_recipient_mode(tmp.path()).unwrap(), None);
616 }
617
618 /// Lock in the exact user-facing Display text for every `ProgressEvent`
619 /// variant. CLI and desktop surface `{event}` directly, so a silent
620 /// wording change would be a visible UX regression and a format-level
621 /// regression for any tooling that parses the strings. If a message
622 /// needs to change, update this test in the same commit so the intent
623 /// is reviewable.
624 #[test]
625 fn progress_events_display_exact_strings() {
626 assert_eq!(
627 ProgressEvent::DerivingPassphraseWrapKey.to_string(),
628 "Deriving passphrase key\u{2026}"
629 );
630 assert_eq!(
631 ProgressEvent::UnlockingPrivateKey.to_string(),
632 "Unlocking private key\u{2026}"
633 );
634 assert_eq!(ProgressEvent::Encrypting.to_string(), "Encrypting\u{2026}");
635 assert_eq!(ProgressEvent::Decrypting.to_string(), "Decrypting\u{2026}");
636 assert_eq!(
637 ProgressEvent::GeneratingKeyPair.to_string(),
638 "Generating key pair\u{2026}"
639 );
640 assert_eq!(
641 ProgressEvent::BytesProcessed { done: 2, total: 3 }.to_string(),
642 "66%"
643 );
644 }
645
646 /// `decode_x25519_recipient_string` shares the canonical
647 /// `decode_x25519_recipient` path with `PublicKey::from_recipient_string`,
648 /// so it must inherit the all-zero input rejection. Pin the contract
649 /// directly at the free-function entry so a future refactor that bypasses
650 /// the canonical decoder cannot let a degenerate value through this
651 /// surface.
652 #[test]
653 fn decode_x25519_recipient_string_rejects_all_zero_public_key() {
654 let s = key::public::encode_recipient_string_unchecked(
655 recipient::x25519::TYPE_NAME,
656 &[0u8; 32],
657 )
658 .unwrap();
659 match decode_x25519_recipient_string(&s) {
660 Err(CryptoError::InvalidFormat(FormatDefect::MalformedPublicKey)) => {}
661 other => panic!("expected MalformedPublicKey, got {other:?}"),
662 }
663 }
664
665 /// Pin `UnauthenticatedRecipientMode`'s rendered strings at the type's
666 /// home so a future variant rename or label tweak surfaces here, not only
667 /// via the indirect `DecryptorModeMismatch` Display test in `error.rs`.
668 /// `#[non_exhaustive]` is irrelevant inside the defining crate — adding a
669 /// new variant produces a compile error here until the test handles it.
670 #[test]
671 fn unauthenticated_recipient_mode_display_pinned_strings() {
672 assert_eq!(
673 UnauthenticatedRecipientMode::Passphrase.to_string(),
674 "passphrase"
675 );
676 assert_eq!(
677 UnauthenticatedRecipientMode::PublicKey.to_string(),
678 "public-key"
679 );
680 match UnauthenticatedRecipientMode::Passphrase {
681 UnauthenticatedRecipientMode::Passphrase | UnauthenticatedRecipientMode::PublicKey => {}
682 }
683 }
684
685 /// Mirror the `UnauthenticatedRecipientMode` Display pin for the
686 /// authenticated kind discriminant. The strings are deliberately
687 /// identical to the unauthenticated side so downstream rendering
688 /// (logs, audit trails) does not need to branch on authentication
689 /// state. The two enums (`UnauthenticatedRecipientMode` and
690 /// `AuthenticatedRecipientModeKind`) keep separate Display impls so
691 /// either side can drift without dragging the other; the wrapper
692 /// `AuthenticatedRecipientMode::Display` delegates to its `kind`, so
693 /// the wrapper inherits whatever the discriminant prints.
694 #[test]
695 fn authenticated_recipient_mode_display_pinned_strings() {
696 assert_eq!(
697 AuthenticatedRecipientModeKind::Passphrase.to_string(),
698 "passphrase"
699 );
700 assert_eq!(
701 AuthenticatedRecipientModeKind::PublicKey.to_string(),
702 "public-key"
703 );
704 // Wrapper delegates to its kind.
705 assert_eq!(
706 AuthenticatedRecipientMode::passphrase().to_string(),
707 "passphrase"
708 );
709 assert_eq!(
710 AuthenticatedRecipientMode::public_key().to_string(),
711 "public-key"
712 );
713 }
714
715 /// Lock in the kind discriminator so the public exhaustive-match surface
716 /// stays a stable shape: callers use `kind()` to switch on the variant
717 /// without touching the sealed wrapper.
718 #[test]
719 fn authenticated_recipient_mode_kind_round_trips() {
720 assert_eq!(
721 AuthenticatedRecipientMode::passphrase().kind(),
722 AuthenticatedRecipientModeKind::Passphrase
723 );
724 assert_eq!(
725 AuthenticatedRecipientMode::public_key().kind(),
726 AuthenticatedRecipientModeKind::PublicKey
727 );
728 assert!(AuthenticatedRecipientMode::passphrase().is_passphrase());
729 assert!(!AuthenticatedRecipientMode::passphrase().is_public_key());
730 assert!(AuthenticatedRecipientMode::public_key().is_public_key());
731 assert!(!AuthenticatedRecipientMode::public_key().is_passphrase());
732 }
733}