use zip::CompressionMethod;
use crate::classify::classify;
use crate::decrypt::{decrypt, DecryptError};
use crate::encrypt::{
encrypt, encrypt_with_params, Argon2Axis, Argon2Params, EncryptError, ParamsReason,
};
use crate::test_support::{
append_stored_member, goldens_dir, load_golden, read_member, strict_b64_decode, zip_method,
zip_namelist, zip_with, zip_with_methods, MIME_TEXT, NONASCII_PASSWORD, PASSWORD,
};
use crate::{Checksum, Cipher, Kdf, Mode, StartKeyAlg};
#[test]
fn s1_already_encrypted_wholesome() {
let err = encrypt(&load_golden("lo-wholesome-gcm-argon2.odt"), PASSWORD).unwrap_err();
assert!(matches!(err, EncryptError::AlreadyEncrypted));
}
#[test]
fn s1_empty_password() {
let err = encrypt(&load_golden("lo-unencrypted.odt"), "").unwrap_err();
assert!(matches!(err, EncryptError::EmptyPassword));
}
#[test]
fn odf12_fatal_plain_package_is_refused() {
let blob = append_stored_member(&load_golden("lo-unencrypted.odt"), "extra.bin", b"nope");
let class = classify(&blob).expect("fixture classifies");
assert_eq!(class.mode, Mode::Plain);
assert!(
class.odf12_fatal,
"unlisted root stream on ODF 1.4 must be fatal"
);
assert!(matches!(
encrypt(&blob, PASSWORD).unwrap_err(),
EncryptError::Odf12Fatal
));
}
#[test]
fn s1_classify_failure_is_reported_as_classify() {
let err = encrypt(b"not a zip at all", PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::Classify(crate::DetectError::NotZip)),
"expected Classify(NotZip), got {err:?}"
);
let bare = zip_with(&[("content.xml", b"<x/>")]);
let err = encrypt(&bare, PASSWORD).unwrap_err();
assert!(
matches!(
err,
EncryptError::Classify(crate::DetectError::MissingManifest)
),
"expected Classify(MissingManifest), got {err:?}"
);
}
#[test]
fn s1_pgp_package_is_already_encrypted() {
let pgp = crate::test_support::pgp_two_row_zip();
assert_ne!(
classify(&pgp).expect("pgp zip classifies").mode,
Mode::Plain
);
let err = encrypt(&pgp, PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::AlreadyEncrypted),
"expected AlreadyEncrypted, got {err:?}"
);
}
#[test]
fn s1_encrypted_rows_without_a_latch_are_partially_encrypted() {
let manifest = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
<manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="{MIME_TEXT}"/>
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
<manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml" manifest:size="64">
<manifest:encryption-data manifest:checksum-type="{sha1_1k}" manifest:checksum="{b64}">
<manifest:algorithm manifest:algorithm-name="{aes}" manifest:initialisation-vector="{b64}"/>
<manifest:start-key-generation manifest:start-key-generation-name="{sha1}"/>
<manifest:key-derivation manifest:key-derivation-name="{pbkdf2}" manifest:salt="{b64}" manifest:iteration-count="1024" manifest:key-size="32"/>
</manifest:encryption-data>
</manifest:file-entry>
</manifest:manifest>
"#,
sha1_1k = crate::uris::SHA1_1K_NAME,
aes = crate::uris::AES256_URL,
sha1 = crate::uris::SHA1_NAME,
pbkdf2 = crate::uris::PBKDF2_NAME,
b64 = crate::test_support::B64,
);
let pkg = zip_with(&[
("mimetype", MIME_TEXT.as_bytes()),
("META-INF/manifest.xml", manifest.as_bytes()),
("content.xml", b"x"),
("styles.xml", b"y"),
]);
let class = classify(&pkg).expect("constructed package classifies");
assert_eq!(class.mode, Mode::PerEntry, "rows exist, so PerEntry");
assert!(
!class.package_encrypted,
"no row on content.xml or encrypted-package, so no latch"
);
assert!(!class.encrypted_entries.is_empty());
let err = encrypt(&pkg, PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::PartiallyEncrypted),
"expected PartiallyEncrypted, got {err:?}"
);
assert!(
err.to_string().contains("never prompts"),
"message must not claim the package is encrypted: {err}"
);
}
#[test]
fn s1_a_latched_package_is_still_already_encrypted() {
let sealed = encrypt(&load_golden("lo-unencrypted.odt"), PASSWORD).expect("seals");
assert!(classify(&sealed).expect("classifies").package_encrypted);
assert!(matches!(
encrypt(&sealed, PASSWORD).unwrap_err(),
EncryptError::AlreadyEncrypted
));
}
#[derive(Default, Debug)]
struct ManifestCheck {
root_version: Option<String>,
root_has_loext_ns: bool,
file_entry_count: usize,
full_path: Option<String>,
size: Option<String>,
media_type: Option<String>,
checksum_type: Option<String>,
checksum: Option<String>,
child_order: Vec<String>,
algorithm_name: Option<String>,
iv: Option<String>,
start_key_name: Option<String>,
start_key_size: Option<String>,
kdf_name: Option<String>,
argon2_t: Option<String>,
argon2_m: Option<String>,
argon2_p: Option<String>,
salt: Option<String>,
kdf_key_size: Option<String>,
}
fn check_manifest(xml: &[u8]) -> ManifestCheck {
use quick_xml::events::Event;
use quick_xml::Reader;
fn attr(e: &quick_xml::events::BytesStart<'_>, key: &str) -> Option<String> {
e.attributes()
.flatten()
.find(|a| a.key.as_ref() == key.as_bytes())
.map(|a| String::from_utf8_lossy(a.value.as_ref()).into_owned())
}
let mut reader = Reader::from_reader(xml);
reader.config_mut().trim_text(true);
let mut buf = Vec::new();
let mut out = ManifestCheck::default();
let mut in_encryption_data = false;
loop {
buf.clear();
match reader.read_event_into(&mut buf) {
Ok(Event::Eof) => break,
Ok(Event::Start(e)) | Ok(Event::Empty(e)) => {
let name = String::from_utf8_lossy(e.name().as_ref()).into_owned();
match name.as_str() {
"manifest:manifest" => {
out.root_version = attr(&e, "manifest:version");
out.root_has_loext_ns = e.attributes().flatten().any(|a| {
a.key.as_ref() == b"xmlns:loext"
&& a.value.as_ref() == crate::uris::MANIFEST_NS_LOEXT.as_bytes()
});
}
"manifest:file-entry" => {
out.file_entry_count += 1;
out.full_path = attr(&e, "manifest:full-path");
out.size = attr(&e, "manifest:size");
out.media_type = attr(&e, "manifest:media-type");
}
"manifest:encryption-data" => {
in_encryption_data = true;
out.checksum_type = attr(&e, "manifest:checksum-type");
out.checksum = attr(&e, "manifest:checksum");
}
"manifest:algorithm" if in_encryption_data => {
out.child_order.push("algorithm".into());
out.algorithm_name = attr(&e, "manifest:algorithm-name");
out.iv = attr(&e, "manifest:initialisation-vector");
}
"manifest:start-key-generation" if in_encryption_data => {
out.child_order.push("start-key-generation".into());
out.start_key_name = attr(&e, "manifest:start-key-generation-name");
out.start_key_size = attr(&e, "manifest:key-size");
}
"manifest:key-derivation" if in_encryption_data => {
out.child_order.push("key-derivation".into());
out.kdf_name = attr(&e, "manifest:key-derivation-name");
out.argon2_t = attr(&e, "loext:argon2-iterations");
out.argon2_m = attr(&e, "loext:argon2-memory");
out.argon2_p = attr(&e, "loext:argon2-lanes");
out.salt = attr(&e, "manifest:salt");
out.kdf_key_size = attr(&e, "manifest:key-size");
}
_ => {}
}
}
Ok(Event::End(e)) => {
if e.name().as_ref() == b"manifest:encryption-data" {
in_encryption_data = false;
}
}
Ok(_) => {}
Err(e) => panic!("manifest.xml parse error: {e}"),
}
}
out
}
#[test]
fn s2_wholesome_emit_matches_table() {
let input = load_golden("lo-unencrypted.odt");
let input_mimetype = read_member(&input, "mimetype");
let out = encrypt(&input, PASSWORD).expect("encrypt");
assert_eq!(
zip_namelist(&out),
vec!["mimetype", "encrypted-package", "META-INF/manifest.xml"]
);
assert_eq!(zip_method(&out, "mimetype"), CompressionMethod::Stored);
assert_eq!(
zip_method(&out, "encrypted-package"),
CompressionMethod::Stored
);
assert_eq!(
zip_method(&out, "META-INF/manifest.xml"),
CompressionMethod::Deflated
);
assert_eq!(read_member(&out, "mimetype"), input_mimetype);
let mf_bytes = read_member(&out, "META-INF/manifest.xml");
let mf = check_manifest(&mf_bytes);
assert_eq!(mf.root_version.as_deref(), Some("1.4"));
assert!(mf.root_has_loext_ns, "xmlns:loext must be present: {mf:?}");
assert_eq!(
mf.file_entry_count, 1,
"wholesome writes exactly one file-entry, no root \"/\" row: {mf:?}"
);
assert_eq!(mf.full_path.as_deref(), Some("encrypted-package"));
assert_eq!(mf.size.as_deref(), Some(input.len().to_string().as_str()));
assert_eq!(
mf.media_type.as_deref(),
Some(String::from_utf8_lossy(&input_mimetype).as_ref())
);
assert!(
mf.checksum_type.is_none() && mf.checksum.is_none(),
"GCM writes no checksum attributes at all: {mf:?}"
);
assert_eq!(
mf.child_order,
vec!["algorithm", "start-key-generation", "key-derivation"]
);
assert_eq!(
mf.algorithm_name.as_deref(),
Some("http://www.w3.org/2009/xmlenc11#aes256-gcm")
);
let iv = strict_b64_decode(mf.iv.as_deref().expect("iv present")).expect("IV is strict base64");
assert_eq!(iv.len(), 12, "IV must be 12 random bytes");
assert_eq!(
mf.start_key_name.as_deref(),
Some("http://www.w3.org/2001/04/xmlenc#sha256"),
"must be the W3C SHA-256 URL, not the ODF12 xmldsig one"
);
assert_eq!(mf.start_key_size.as_deref(), Some("32"));
assert_eq!(
mf.kdf_name.as_deref(),
Some("urn:org:documentfoundation:names:experimental:office:manifest:argon2id")
);
assert_eq!(mf.argon2_t.as_deref(), Some("3"));
assert_eq!(mf.argon2_m.as_deref(), Some("65536"));
assert_eq!(mf.argon2_p.as_deref(), Some("4"));
let salt = strict_b64_decode(mf.salt.as_deref().expect("salt present"))
.expect("salt is strict base64");
assert_eq!(salt.len(), 16, "salt must be 16 random bytes");
assert_eq!(mf.kdf_key_size.as_deref(), Some("32"));
let after = classify(&out).expect("output classifies");
assert_eq!(after.mode, Mode::Wholesome);
assert_eq!(after.encrypted_entries.len(), 1);
let row = &after.encrypted_entries[0];
assert_eq!(row.path, "encrypted-package");
assert_eq!(row.cipher, Cipher::AesGcmW3c);
match &row.kdf {
Kdf::Argon2id { t, m, p, salt } => {
assert_eq!(*t, 3);
assert_eq!(*m, 65536);
assert_eq!(*p, 4);
assert_eq!(salt.len(), 16);
}
other => panic!("expected Kdf::Argon2id, got {other:?}"),
}
assert_eq!(row.start_key, StartKeyAlg::Sha256);
assert_eq!(row.checksum, Checksum::None);
assert_eq!(row.derived_key_len, 32);
assert_eq!(row.size, input.len() as i64);
assert_eq!(
after.odf_version.as_deref(),
Some("1.4"),
"wholesome writes manifest:version=\"1.4\""
);
assert!(
!after.has_unexpected_streams,
"a three-member wholesome package has no unexpected ODF 1.2 streams"
);
}
#[test]
fn s2_salt_and_iv_are_fresh_per_call() {
let input = load_golden("lo-unencrypted.odt");
let a = encrypt(&input, PASSWORD).expect("encrypt a");
let b = encrypt(&input, PASSWORD).expect("encrypt b");
let mf_a = check_manifest(&read_member(&a, "META-INF/manifest.xml"));
let mf_b = check_manifest(&read_member(&b, "META-INF/manifest.xml"));
assert_ne!(mf_a.iv, mf_b.iv, "IV must be fresh per encrypt() call");
assert_ne!(
mf_a.salt, mf_b.salt,
"salt must be fresh per encrypt() call"
);
}
#[test]
fn s2_no_mimetype_member_falls_back_to_classify_media_type() {
let media_type = MIME_TEXT;
let manifest = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.4">
<manifest:file-entry manifest:full-path="/" manifest:media-type="{media_type}"/>
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
"#
);
let input = zip_with(&[
("META-INF/manifest.xml", manifest.as_bytes()),
("content.xml", b"<office:document-content/>"),
]);
let before = classify(&input).expect("constructed fixture classifies");
assert_eq!(before.mode, Mode::Plain, "fixture must be Mode::Plain");
assert_eq!(before.media_type.as_deref(), Some(media_type));
assert!(
!zip_namelist(&input).iter().any(|n| n == "mimetype"),
"fixture must have no raw mimetype member"
);
let out = encrypt(&input, PASSWORD).expect("encrypt");
let mf = check_manifest(&read_member(&out, "META-INF/manifest.xml"));
assert_eq!(mf.media_type.as_deref(), Some(media_type));
assert_eq!(
read_member(&out, "mimetype"),
media_type.as_bytes(),
"mimetype member falls back to classify's media_type, raw UTF-8, no trailing newline"
);
}
#[test]
fn s4_wrong_password_after_encrypt() {
let original = load_golden("lo-unencrypted.odt");
let encrypted = encrypt(&original, PASSWORD).expect("encrypt");
let err = decrypt(&encrypted, "wrong").unwrap_err();
assert!(
matches!(err, DecryptError::WrongPassword),
"expected DecryptError::WrongPassword, got {err:?}"
);
}
#[test]
fn s4_encrypt_refuses_every_already_encrypted_golden() {
let dir = goldens_dir();
let names: Vec<String> = std::fs::read_dir(&dir)
.unwrap()
.filter_map(|e| e.ok())
.filter(|e| e.path().extension().map(|x| x == "odt").unwrap_or(false))
.map(|e| e.file_name().to_string_lossy().into_owned())
.collect();
assert!(
!names.is_empty(),
"sweep found no *.odt files under {dir:?} -- the directory itself is broken"
);
let mut already_encrypted_count = 0usize;
for name in &names {
let bytes = load_golden(name);
let class = classify(&bytes).unwrap_or_else(|e| panic!("{name}: {e}"));
if class.mode == Mode::Plain {
continue;
}
already_encrypted_count += 1;
let err = encrypt(&bytes, PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::AlreadyEncrypted),
"{name}: expected AlreadyEncrypted, got {err:?}"
);
}
assert!(
already_encrypted_count > 0,
"swept {} goldens ({names:?}) but none classified as already-encrypted -- \
the sweep itself is broken, not exercising this test's negative",
names.len()
);
eprintln!(
"s4_encrypt_refuses_every_already_encrypted_golden: {already_encrypted_count} of {} \
goldens under {dir:?} classified as already-encrypted and were refused by encrypt()",
names.len()
);
}
#[test]
fn s3_round_trip_byte_identical_lo_unencrypted() {
let original = load_golden("lo-unencrypted.odt");
let encrypted = encrypt(&original, PASSWORD).expect("encrypt");
let round_tripped = decrypt(&encrypted, PASSWORD).expect("decrypt");
assert_eq!(
round_tripped, original,
"decrypt(encrypt(p, pw), pw) must be byte-identical to p"
);
}
fn nontrivial_plain_fixture() -> Vec<u8> {
let media_type = "application/vnd.oasis.opendocument.text";
let manifest = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">
<manifest:file-entry manifest:full-path="/" manifest:version="1.3" manifest:media-type="{media_type}"/>
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
<manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml"/>
<manifest:file-entry manifest:full-path="meta.xml" manifest:media-type="text/xml"/>
<manifest:file-entry manifest:full-path="Pictures/image.png" manifest:media-type="image/png"/>
</manifest:manifest>
"#
);
let content_xml = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0">
<office:body>
<office:text>
<text:p>Café résumé 日本語 🎉</text:p>
</office:text>
</office:body>
</office:document-content>
"#;
let styles_xml = r#"<?xml version="1.0" encoding="UTF-8"?><office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"/>"#;
let meta_xml = r#"<?xml version="1.0" encoding="UTF-8"?><office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0"/>"#;
let mut image_png: Vec<u8> = vec![0x89, b'P', b'N', b'G', 0x0d, 0x0a, 0x1a, 0x0a];
image_png.extend((0u32..512).map(|i| (i % 256) as u8));
let manifest = manifest.into_bytes();
zip_with_methods(&[
("mimetype", media_type.as_bytes(), CompressionMethod::Stored),
(
"META-INF/manifest.xml",
&manifest,
CompressionMethod::Deflated,
),
(
"content.xml",
content_xml.as_bytes(),
CompressionMethod::Deflated,
),
(
"styles.xml",
styles_xml.as_bytes(),
CompressionMethod::Deflated,
),
("meta.xml", meta_xml.as_bytes(), CompressionMethod::Deflated),
(
"Pictures/image.png",
&image_png,
CompressionMethod::Deflated,
),
])
}
#[test]
fn s5_checked_in_evidence_still_decrypts_to_its_source_golden() {
let evidence = load_golden("lo-opens-our-encrypt-output.odt");
let source = load_golden("lo-unencrypted.odt");
assert_eq!(
classify(&evidence).expect("evidence classifies").mode,
Mode::Wholesome
);
assert_eq!(
decrypt(&evidence, PASSWORD).expect("evidence decrypts"),
source,
"tests/goldens/lo-opens-our-encrypt-output.odt must decrypt to \
lo-unencrypted.odt byte-for-byte -- regenerate it with \
tests/goldens/validate_encrypt.py if encrypt's framing changed"
);
}
#[test]
fn mimetype_over_ceiling_is_refused() {
let mut mimetype = MIME_TEXT.as_bytes().to_vec();
mimetype.resize(2048, b'x');
let manifest = r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.4">
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
"#;
let input = zip_with_methods(&[
("mimetype", &mimetype, CompressionMethod::Deflated),
(
"META-INF/manifest.xml",
manifest.as_bytes(),
CompressionMethod::Deflated,
),
(
"content.xml",
b"<office:document-content/>",
CompressionMethod::Deflated,
),
]);
assert_eq!(
classify(&input).expect("fixture classifies").mode,
Mode::Plain
);
let err = encrypt(&input, PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::Mimetype(_)),
"expected Mimetype, got {err:?}"
);
}
#[test]
fn mimetype_with_non_xml_char_is_refused() {
let mut mimetype = MIME_TEXT.as_bytes().to_vec();
mimetype.push(0);
let manifest = r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.4">
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
"#;
let input = zip_with_methods(&[
("mimetype", &mimetype, CompressionMethod::Stored),
(
"META-INF/manifest.xml",
manifest.as_bytes(),
CompressionMethod::Deflated,
),
(
"content.xml",
b"<office:document-content/>",
CompressionMethod::Deflated,
),
]);
assert_eq!(
classify(&input).expect("fixture classifies").mode,
Mode::Plain,
"classify tolerates the NUL -- its check is starts_with(\"application/vnd.\")"
);
let err = encrypt(&input, PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::Mimetype(_)),
"expected Mimetype, got {err:?}"
);
}
#[test]
fn whitespace_unstable_mimetype_is_refused() {
for (label, suffix) in [("newline", "\n"), ("tab", "\t"), ("carriage return", "\r")] {
let mimetype = format!("{MIME_TEXT}{suffix}").into_bytes();
let manifest = r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.4">
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
"#;
let input = zip_with_methods(&[
("mimetype", &mimetype, CompressionMethod::Stored),
(
"META-INF/manifest.xml",
manifest.as_bytes(),
CompressionMethod::Deflated,
),
(
"content.xml",
b"<office:document-content/>",
CompressionMethod::Deflated,
),
]);
assert_eq!(
classify(&input).expect("fixture classifies").mode,
Mode::Plain,
"{label}: classify tolerates it -- that is why encrypt has to not"
);
let err = encrypt(&input, PASSWORD).unwrap_err();
assert!(
matches!(err, EncryptError::Mimetype(_)),
"{label}: expected Mimetype, got {err:?}"
);
}
}
#[test]
fn unusual_but_legal_mimetype_is_still_copied_verbatim() {
let mimetype = b"application/vnd.oasis.opendocument.text;version=1.4+odd".to_vec();
let manifest = r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.4">
<manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
"#;
let input = zip_with_methods(&[
("mimetype", &mimetype, CompressionMethod::Stored),
(
"META-INF/manifest.xml",
manifest.as_bytes(),
CompressionMethod::Deflated,
),
(
"content.xml",
b"<office:document-content/>",
CompressionMethod::Deflated,
),
]);
assert_eq!(
classify(&input).expect("fixture classifies").mode,
Mode::Plain
);
let out = encrypt(&input, PASSWORD).expect("encrypt");
assert_eq!(
read_member(&out, "mimetype"),
mimetype,
"an attribute-stable mimetype is the input's own bytes, copied, not re-derived"
);
let mf = check_manifest(&read_member(&out, "META-INF/manifest.xml"));
assert_eq!(
mf.media_type.as_deref(),
Some(std::str::from_utf8(&mimetype).unwrap()),
"the parsed attribute must equal the verbatim member bytes"
);
assert_eq!(decrypt(&out, PASSWORD).expect("decrypt"), input);
}
#[test]
fn round_trip_under_a_non_ascii_password() {
let original = load_golden("lo-unencrypted.odt");
let encrypted = encrypt(&original, NONASCII_PASSWORD).expect("encrypt");
assert_eq!(
decrypt(&encrypted, NONASCII_PASSWORD).expect("decrypt"),
original
);
assert!(matches!(
decrypt(&encrypted, PASSWORD).unwrap_err(),
DecryptError::WrongPassword
));
}
#[test]
fn deflate_ceiling_refuses_an_oversized_buffer() {
let plain = load_golden("lo-unencrypted.odt");
let n = plain.len() as u64;
let cheap = Argon2Params::new(1, 8, 1).unwrap();
assert!(
crate::encrypt_stream::encrypt_slice(&plain, PASSWORD, cheap, n).is_ok(),
"at the ceiling must encrypt"
);
let err = crate::encrypt_stream::encrypt_slice(&plain, PASSWORD, cheap, n - 1).unwrap_err();
match err {
EncryptError::Deflate(msg) => {
assert!(
msg.contains(&n.to_string()) && msg.contains(&(n - 1).to_string()),
"message: {msg}"
)
}
other => panic!("expected Deflate, got {other:?}"),
}
}
#[test]
fn s3_round_trip_byte_identical_nontrivial_fixture() {
let original = nontrivial_plain_fixture();
let before = classify(&original).expect("fixture classifies");
assert_eq!(before.mode, Mode::Plain, "fixture must be Mode::Plain");
assert!(before.encrypted_entries.is_empty());
let encrypted = encrypt(&original, PASSWORD).expect("encrypt");
let round_tripped = decrypt(&encrypted, PASSWORD).expect("decrypt");
assert_eq!(
round_tripped, original,
"decrypt(encrypt(p, pw), pw) must be byte-identical to p"
);
}
#[test]
fn default_params_match_what_encrypt_writes_on_its_own() {
let sealed = encrypt(&load_golden("lo-unencrypted.odt"), PASSWORD).expect("encrypt");
let row = classify(&sealed)
.expect("classify")
.common
.expect("latch row");
let d = Argon2Params::LIBREOFFICE_DEFAULT;
assert_eq!((d.t(), d.m_kib(), d.p()), (3, 65536, 4));
assert!(
matches!(row.kdf, Kdf::Argon2id { t, m, p, .. } if (t, m, p) == (d.t(), d.m_kib(), d.p())),
"encrypt() must write LIBREOFFICE_DEFAULT, got {:?}",
row.kdf
);
}
#[test]
fn caller_params_reach_both_the_manifest_and_the_derivation() {
let plain = load_golden("lo-unencrypted.odt");
let params = Argon2Params::new(2, 8192, 2).expect("valid tuple");
let sealed = encrypt_with_params(&plain, PASSWORD, params).expect("encrypt");
let row = classify(&sealed)
.expect("classify")
.common
.expect("latch row");
assert!(
matches!(
row.kdf,
Kdf::Argon2id {
t: 2,
m: 8192,
p: 2,
..
}
),
"manifest must record the caller's tuple, got {:?}",
row.kdf
);
assert_eq!(
decrypt(&sealed, PASSWORD).expect("decrypt"),
plain,
"a package derived at a caller-chosen cost must still round-trip"
);
}
#[test]
fn weak_but_runnable_params_are_accepted() {
let params = Argon2Params::new(1, 8, 1).expect("m = 8 * p exactly, argon2's floor");
assert!(params.is_weaker_than_libreoffice());
let plain = load_golden("lo-unencrypted.odt");
let sealed = encrypt_with_params(&plain, PASSWORD, params).expect("weak must not be refused");
assert_eq!(decrypt(&sealed, PASSWORD).expect("decrypt"), plain);
}
#[test]
fn the_refusal_reason_names_whose_rule_it_was() {
assert!(
Argon2Params::new(i32::MAX, 65536, 4).is_ok(),
"the write path stopped capping t in rc.6; the read path's cap is DecryptLimits::argon2_max_t"
);
match Argon2Params::new(0, 65536, 4) {
Err(EncryptError::Params(ParamsReason::OutOfRange { axis, got, .. })) => {
assert_eq!(axis, Argon2Axis::T);
assert_eq!(got, 0, "zero is not a positiveInteger");
}
other => panic!("expected OutOfRange on t, got {other:?}"),
}
match Argon2Params::new(3, 8, 4) {
Err(EncryptError::Params(ParamsReason::CipherRejects { axis, got, min, .. })) => {
assert_eq!(axis, Argon2Axis::MKib);
assert_eq!(got, 8);
assert_eq!(min, 32, "8 * p");
}
other => panic!("expected CipherRejects on m, got {other:?}"),
}
let ours = Argon2Params::new(0, 65536, 4).unwrap_err().to_string();
assert!(ours.contains("this crate acts on"), "{ours}");
let theirs = Argon2Params::new(3, 8, 4).unwrap_err().to_string();
assert!(theirs.contains("argon2 itself requires"), "{theirs}");
}
#[test]
fn params_are_refused_only_when_argon2_cannot_run_them() {
assert!(matches!(
Argon2Params::new(3, 8, 4),
Err(EncryptError::Params(_))
));
assert!(matches!(
Argon2Params::new(0, 65536, 4),
Err(EncryptError::Params(_))
));
assert!(matches!(
Argon2Params::new(3, -1, 4),
Err(EncryptError::Params(_))
));
assert!(Argon2Params::new(1, 32, 4).is_ok());
}
#[test]
fn is_weaker_is_any_axis_below_not_a_strength_ordering() {
let stronger_t = Argon2Params::new(4, 65536, 4).unwrap();
assert!(
!stronger_t.is_weaker_than_libreoffice(),
"stronger on t, identical elsewhere, must not report weaker"
);
let fewer_passes_double_memory = Argon2Params::new(2, 131_072, 4).unwrap();
assert!(
fewer_passes_double_memory.is_weaker_than_libreoffice(),
"any axis below the reference reports weaker, even when another is well above"
);
}
#[test]
fn is_weaker_than_libreoffice_reports_but_does_not_gate() {
assert!(!Argon2Params::LIBREOFFICE_DEFAULT.is_weaker_than_libreoffice());
assert!(Argon2Params::new(2, 65536, 4)
.unwrap()
.is_weaker_than_libreoffice());
assert!(Argon2Params::new(3, 8192, 4)
.unwrap()
.is_weaker_than_libreoffice());
assert!(Argon2Params::new(3, 65536, 2)
.unwrap()
.is_weaker_than_libreoffice());
assert!(!Argon2Params::new(4, 131_072, 4)
.unwrap()
.is_weaker_than_libreoffice());
}
#[test]
fn rfc9106_first_recommended_tuple_is_accepted() {
let p = Argon2Params::new(1, 2_097_152, 4).expect("RFC 9106 §4 first recommended option");
assert_eq!(p.t(), 1);
assert_eq!(p.m_kib(), 2_097_152);
assert_eq!(p.p(), 4);
}
#[test]
fn the_rfcs_larger_examples_are_accepted_as_well() {
for m_kib in [1 << 22, 6 * 1024 * 1024] {
assert!(
Argon2Params::new(1, m_kib, 4).is_ok(),
"m = {m_kib} KiB must not be refused by a bound of ours"
);
}
}
#[test]
fn the_remaining_memory_ceiling_is_the_field_width() {
assert_eq!(
crate::limits::ARGON2_MAX_M_COST_KIB_WRITE,
i32::MAX as u32,
"the write ceiling must BE the field width, not merely be at least it -- `limits.rs` justifies keeping the check by the range an error reports"
);
assert!(
Argon2Params::new(1, i32::MAX, 4).is_ok(),
"and nothing of ours may sit below it"
);
}
#[test]
fn what_refuses_a_memory_value_now_is_the_cipher_or_the_format() {
let err = Argon2Params::new(1, 8, 4).expect_err("m = 8 with p = 4 is below argon2's own floor");
assert!(
matches!(
err,
EncryptError::Params(ParamsReason::CipherRejects {
axis: Argon2Axis::MKib,
..
})
),
"argon2's own requirement must not be reported as ours, got {err:?}"
);
let err = Argon2Params::new(1, 0, 1).expect_err("zero is not a positive integer");
assert!(
matches!(
err,
EncryptError::Params(ParamsReason::OutOfRange {
axis: Argon2Axis::MKib,
..
})
),
"got {err:?}"
);
let err = Argon2Params::new(1, -1, 1).expect_err("negative is not a positive integer");
assert!(matches!(
err,
EncryptError::Params(ParamsReason::OutOfRange { .. })
));
}
#[test]
fn the_t_ceiling_still_refuses_the_expensive_direction() {
assert!(
Argon2Params::new(3, 65536, 4).is_ok(),
"LibreOffice's own tuple must pass"
);
assert_eq!(crate::limits::ARGON2_MAX_T_COST_WRITE, i32::MAX as u32);
assert!(
Argon2Params::new(65_536, 65536, 4).is_ok(),
"a caller's own t is theirs to pick"
);
let err = Argon2Params::new(-1, 65536, 4).expect_err("negative is not a positive integer");
assert!(
matches!(
err,
EncryptError::Params(ParamsReason::OutOfRange {
axis: Argon2Axis::T,
..
})
),
"and it is reported as OURS, because it is: {err:?}"
);
}
#[test]
fn every_encrypt_error_variant_is_accounted_for_in_the_cli_exit_map() {
fn accounted_for(e: &EncryptError) {
match e {
EncryptError::Classify(_) => (),
EncryptError::AlreadyEncrypted => (),
EncryptError::PartiallyEncrypted => (),
EncryptError::Odf12Fatal => (),
EncryptError::EmptyPassword => (),
EncryptError::Random(_) => (),
EncryptError::Params(_) => (),
EncryptError::HostCannotAllocate { .. } => (),
EncryptError::Deflate(_) => (),
EncryptError::Mimetype(_) => (),
EncryptError::Zip(_) => (),
EncryptError::Internal(_) => (),
EncryptError::Io(_) => (),
}
}
accounted_for(&EncryptError::AlreadyEncrypted);
}
#[test]
fn encrypt_output_has_no_non_encrypted_entries() {
let encrypted = encrypt(&load_golden("lo-unencrypted.odt"), PASSWORD).expect("encrypt");
let class = classify(&encrypted).expect("classifies");
assert!(class.package_encrypted);
assert!(!class.has_non_encrypted_entries);
}