kplib 0.20.2

Hardened KDBX database file parser
Documentation
//! Regression tests for `Database::save` output being accepted by
//! KeePassXC 2.7+. Two writer bugs were diagnosed against the
//! `tests/resources/test_db_kdbx41_features.kdbx` fixture (a real KDBX
//! 4.1 file generated by KeePassXC 2.7.12):
//!
//!   1. Nullable booleans (`EnableSearching`) must
//!      serialize the unset state as the literal string "null", not as
//!      an empty self-closing element. KeePassXC rejects empty
//!      elements with `Invalid <field> value`.
//!
//! This tests assert on the literal XML bytes our writer produces;
//! a parser-level self-roundtrip would not catch either bug because
//! our deserializer is permissive enough to accept both the broken
//! and the correct forms.

#![allow(clippy::expect_used)]

use crate::{Database, DatabaseKey};

const FIXTURE_PATH: &str = "tests/resources/test_db_kdbx41_features.kdbx";
const FIXTURE_PASSWORD: &str = "demopass";

fn load_and_resave_xml() -> String {
	let mut f = std::fs::File::open(FIXTURE_PATH).expect("open fixture");

	let db = Database::open(&mut f, DatabaseKey::new().with_password(FIXTURE_PASSWORD)).expect("parse fixture");

	// These tests inspect XML serialization, not encryption.
	let inner_random_stream_key = [0u8; 32];

	let mut inner_cipher = db.config.inner_cipher_config.get_cipher(&inner_random_stream_key).expect("initialize inner cipher");

	let xml = super::to_xml(&db, &mut *inner_cipher).expect("serialize database to XML");

	String::from_utf8(xml.to_vec()).expect("XML is UTF-8")
}

#[test]
fn enable_searching_unset_serializes_as_literal_null() {
	let xml = load_and_resave_xml();
	assert!(
		xml.contains("<EnableSearching>null</EnableSearching>"),
		"expected '<EnableSearching>null</EnableSearching>'; KeePassXC \
         requires the literal \"null\" string for None and rejects empty \
         self-closing elements with \"Invalid EnableSearching value\". \
         Got XML:\n{}",
		xml,
	);
}