Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
52 changes: 50 additions & 2 deletions interop/native/src/main.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
//! write: creates native-*.db fixture files. read: opens the files the browser tests wrote.
use rusqlite::Connection;
//! write: creates native-*.db fixture files. read: opens the files the browser tests wrote. salt: checks the salts of
//! new databases the unix VFS preallocates.
use rusqlite::{ffi, Connection};
use std::ffi::c_int;

const RAW: &str =
"PRAGMA key = \"x'000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f'\"";
Expand Down Expand Up @@ -372,11 +374,57 @@ fn cmd_read(dir: &str) {
read_settings(dir);
}

/// The chunk size the unix VFS grows a file by, which allocates the header before page 1 is written.
const CHUNK: usize = 65536;

/// Asserts that two new databases under one key draw distinct, nonzero salts while the VFS preallocates in chunks.
fn cmd_salt(dir: &str) {
let salts = ["native-salt-a.db", "native-salt-b.db"].map(|name| {
let path = format!("{dir}/{name}");
let _ = std::fs::remove_file(&path);
let db = open(&path, PASS);
let mut chunk = c_int::try_from(CHUNK).unwrap();
// SAFETY: the handle is the open connection `db` owns and outlives the call, the schema name is a NUL-terminated
// literal, and SQLITE_FCNTL_CHUNK_SIZE reads one c_int through the pointer, which `chunk` provides.
let rc = unsafe {
ffi::sqlite3_file_control(
db.handle(),
c"main".as_ptr(),
ffi::SQLITE_FCNTL_CHUNK_SIZE,
(&raw mut chunk).cast(),
)
};
assert_eq!(rc, ffi::SQLITE_OK, "{name}: SQLITE_FCNTL_CHUNK_SIZE failed");
db.execute_batch("CREATE TABLE t(v TEXT); INSERT INTO t VALUES ('salted');")
.unwrap();
drop(db);
let bytes = std::fs::read(&path).unwrap();
assert_eq!(
bytes.len() % CHUNK,
0,
"{name}: {} bytes, so the chunk size never applied",
bytes.len()
);
let salt: [u8; 16] = bytes[..16].try_into().unwrap();
assert_ne!(salt, [0; 16], "{name} has an all-zero salt");
println!(
"native SQLCipher gave {name} a nonzero salt in a {} byte file",
bytes.len()
);
salt
});
assert_ne!(
salts[0], salts[1],
"two new databases under one key share a salt"
);
}

fn main() {
let dir = std::env::args().nth(2).unwrap();
match std::env::args().nth(1).unwrap().as_str() {
"write" => cmd_write(&dir),
"read" => cmd_read(&dir),
"salt" => cmd_salt(&dir),
_ => unreachable!(),
}
}
6 changes: 6 additions & 0 deletions interop/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,12 @@ cargo run --release --manifest-path "$NATIVE/Cargo.toml" $NATIVE_FEATURES -- wri
(cd web && SQLITE_WASM_RS_SOURCE_DIR="$SOURCE_DIR" wasm-pack test --node --release --test interop --test rusqlite --test settings)
# shellcheck disable=SC2086 # NATIVE_FEATURES is empty or two words.
cargo run --release --manifest-path "$NATIVE/Cargo.toml" $NATIVE_FEATURES -- read "$FIXTURES"
# sqlcipher#633 gives a new database a random salt after the VFS grew it on SQLITE_FCNTL_SIZE_HINT. Only the prerelease
# head may carry it, and the native side is that head only when built from the leg's sources.
if [ -n "${NATIVE_SQLCIPHER_DIR:-}" ] && [ "${SQLCIPHER_LEG:-}" = prerelease ]; then
# shellcheck disable=SC2086 # NATIVE_FEATURES is empty or two words.
cargo run --release --manifest-path "$NATIVE/Cargo.toml" $NATIVE_FEATURES -- salt "$FIXTURES"
fi
# The rest exchange no files with the native side, so one run of them per source directory suffices.
[ -z "${NATIVE_SQLCIPHER_DIR:-}" ] || exit 0
(cd web && SQLITE_WASM_RS_SOURCE_DIR="$SOURCE_DIR" wasm-pack test --node --release \
Expand Down
9 changes: 8 additions & 1 deletion interop/web/build.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,19 @@
//! Sets `sqlcipher_vfs_shim` when a CI leg builds a SQLCipher major that encrypts through its own `sqlciphervfs`.
//! Sets `sqlcipher_vfs_shim` when a CI leg builds a SQLCipher major that encrypts through its own `sqlciphervfs`, and
//! `sqlcipher_size_hint_salt` when the leg carries sqlcipher#633.

fn main() {
println!("cargo::rustc-check-cfg=cfg(sqlcipher_vfs_shim)");
println!("cargo::rustc-check-cfg=cfg(sqlcipher_size_hint_salt)");
println!("cargo::rerun-if-env-changed=SQLCIPHER_LEG_VERSION");
println!("cargo::rerun-if-env-changed=SQLCIPHER_LEG");
let major = std::env::var("SQLCIPHER_LEG_VERSION")
.ok()
.and_then(|version| version.split('.').next()?.parse::<u32>().ok());
if major.is_some_and(|major| major >= 5) {
println!("cargo::rustc-cfg=sqlcipher_vfs_shim");
}
// Only the prerelease head may carry sqlcipher#633, so every other leg and the release skip the salt check.
if std::env::var("SQLCIPHER_LEG").is_ok_and(|leg| leg == "prerelease") {
println!("cargo::rustc-cfg=sqlcipher_size_hint_salt");
}
}
40 changes: 40 additions & 0 deletions interop/web/tests/sahpool.rs
Original file line number Diff line number Diff line change
Expand Up @@ -374,3 +374,43 @@ async fn rekey_on_sahpool() {
util.clear().unwrap();
unsafe { util.uninstall().unwrap() };
}

/// The first 16 bytes of the named file, which hold its salt when no plaintext header is configured.
fn salt(util: &OpfsSAHPoolUtil, name: &str) -> [u8; 16] {
util.export_db(name).unwrap()[..16].try_into().unwrap()
}

#[wasm_bindgen_test]
#[cfg_attr(
not(sqlcipher_size_hint_salt),
ignore = "needs sqlcipher#633, which this SQLCipher lacks"
)]
#[expect(
clippy::future_not_send,
reason = "OpfsSAHPoolUtil uses Rc and is wasm-only"
)]
async fn new_databases_draw_distinct_salts() {
const POOL: &str = "sqlcipher-sahpool-salt";
const VFS: &str = through(POOL);
let util = make_pool(POOL).await;

// sahpool grows a file on SQLITE_FCNTL_SIZE_HINT before page 1 is written, so its header reads back as zeros.
for name in ["salt-a.db", "salt-b.db"] {
let db = Db::open(VFS, name);
db.exec(PASS);
db.exec("PRAGMA journal_mode=DELETE");
db.exec("CREATE TABLE t(id INTEGER PRIMARY KEY, v TEXT)");
populate(&db);
}
let a = salt(&util, "salt-a.db");
let b = salt(&util, "salt-b.db");
assert_ne!(a, [0; 16], "salt-a.db has an all-zero salt");
assert_ne!(b, [0; 16], "salt-b.db has an all-zero salt");
assert_ne!(a, b, "two new databases under one key share a salt");

util.clear().unwrap();
// SAFETY: each connection closed when its `Db` dropped at the end of its loop iteration, this single-threaded
// worker makes no other SQLite call meanwhile, and a sqlciphervfs wrapper only exists on 5.x legs, where the test
// is ignored.
unsafe { util.uninstall().unwrap() };
}
Loading