From 6af752abff9fea613b203eab2930a2053345b10d Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 14:30:47 -0500 Subject: [PATCH 01/18] Add a connection/IO seam for the turso keyring and an in-memory backend TursoKeyring can now adopt an already-open connection (from_connection) or open through a caller-supplied turso IO (with_io), so a browser worker can keep the keyring's secrets table next to its own tables in one OPFS database. Rekey needs cryptex to own the storage, so it reports a clear error for adopted keyrings. turso_common::block_on no longer parks when built for wasm: it polls a bounded number of times and fails instead of spinning forever. The memory backend keeps secrets encrypted in RAM and seals them into a single AEAD blob for export/import, which is the base for browser storage and the JS bindings. CipherAlgorithm moved to its own module so it no longer drags in the page cipher. cargo check --target wasm32-unknown-unknown --no-default-features --features turso passes; a wasm CI job covers it. --- .cargo/config.toml | 8 + .github/workflows/cryptex.yml | 27 +- Cargo.toml | 70 +++- src/keyring.rs | 50 +++ src/keyring/cipher.rs | 45 +++ src/keyring/encrypted_vfs.rs | 2 +- src/keyring/file_common.rs | 130 ++++++- src/keyring/memory.rs | 564 ++++++++++++++++++++++++++++++ src/keyring/page_cipher.rs | 40 +-- src/keyring/turso.rs | 167 ++++++++- src/keyring/turso_common.rs | 175 +++++++-- src/keyring/turso_encrypted_io.rs | 2 +- src/lib.rs | 4 + 13 files changed, 1194 insertions(+), 90 deletions(-) create mode 100644 src/keyring/cipher.rs create mode 100644 src/keyring/memory.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index 60e1f61..b7426a0 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -1,2 +1,10 @@ [target.'cfg(target_arch = "aarch64")'] rustflags = ["--cfg", "aes_armv8"] + +# getrandom 0.3 (through turso_core) needs this cfg to pick its Web Crypto +# backend on wasm32-unknown-unknown. Only a backend selection, never a URL. +[target.wasm32-unknown-unknown] +rustflags = ["--cfg", 'getrandom_backend="wasm_js"'] + +[target.wasm32-wasip1] +runner = "wasmtime" diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index b3400a2..c9c7bd5 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -46,7 +46,7 @@ jobs: - name: Install native dependencies for encrypted-vfs and YubiHSM run: sudo apt-get install -y libclang-dev libusb-1.0-0-dev - run: cargo clippy --no-default-features --features encrypted-vfs -- -D warnings - - run: cargo clippy --all-targets --all-features -- -D warnings + - run: cargo clippy --all-targets --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io" -- -D warnings clippy-macos: runs-on: macos-latest @@ -82,6 +82,27 @@ jobs: - run: cargo clippy --no-default-features --features "windows-credentials,file" -- -D warnings - run: cargo clippy --no-default-features --features encrypted-vfs -- -D warnings + wasm: + runs-on: ubuntu-latest + env: + # The workflow-level RUSTFLAGS override the per-target flags in + # .cargo/config.toml, so the getrandom backend is repeated here. + RUSTFLAGS: '-D warnings --cfg getrandom_backend="wasm_js"' + steps: + - uses: actions/checkout@v4 + - uses: dtolnay/rust-toolchain@master + with: + toolchain: stable + components: clippy + targets: wasm32-unknown-unknown,wasm32-wasip1,wasm32-wasip2 + - name: Check browser and WASI backends + run: | + cargo clippy --target wasm32-unknown-unknown --no-default-features --features turso -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-encrypted-io" -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features memory -- -D warnings + cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" + cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" + rustfmt-linux: runs-on: ubuntu-latest steps: @@ -123,7 +144,7 @@ jobs: - name: Install native dependencies for encrypted-vfs and YubiHSM run: sudo apt-get install -y libclang-dev libusb-1.0-0-dev - run: cargo doc --no-default-features --features encrypted-vfs - - run: cargo doc --no-deps --all-features + - run: cargo doc --no-deps --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io" doc-macos: runs-on: macos-latest @@ -191,7 +212,7 @@ jobs: run: cargo test --test default_argon2_params --no-default-features --features "file,encrypted-vfs" - name: Test all features if: matrix.cache-key == 'encrypted-vfs' - run: cargo test --all-features + run: cargo test --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io" macos: runs-on: macos-latest diff --git a/Cargo.toml b/Cargo.toml index 973373e..fce6107 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -15,8 +15,20 @@ repository = "https://github.com/mikelodder7/cryptex" readme = "README.md" version = "2.4.0" +# `all-features` is not used: the browser-only features (web-storage, +# indexeddb, opfs, js) are rejected on non-wasm targets on purpose. [package.metadata.docs.rs] -all-features = true +no-default-features = true +features = [ + "serde", + "file", + "encrypted-vfs", + "memory", + "turso", + "turso-encrypted-io", + "yubihsm-usb", + "yubihsm-http", +] rustdoc-args = ["--cfg", "docsrs"] [package.metadata.cargo-udeps.ignore] @@ -31,6 +43,18 @@ name = "cryptex" [features] default = ["linux-secret-service", "macos-keychain", "windows-credentials"] file = ["dep:argon2", "dep:dirs", "dep:rusqlite", "rusqlite/bundled-sqlcipher-vendored-openssl"] +memory = ["dep:argon2", "dep:chacha20poly1305", "dep:aes-gcm", "dep:getrandom"] +web-storage = ["memory", "dep:web-sys", "dep:wasm-bindgen"] +indexeddb = ["dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] +opfs = ["dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] +js = [ + "memory", + "indexeddb", + "dep:web-sys", + "dep:wasm-bindgen", + "dep:wasm-bindgen-futures", + "dep:js-sys", +] encrypted-vfs = ["dep:argon2", "dep:dirs", "dep:rusqlite", "rusqlite/bundled", "dep:chacha20poly1305", "dep:aes-gcm", "dep:sqlite-plugin", "dep:getrandom"] turso = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen"] turso-encrypted-io = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen", "dep:chacha20poly1305", "dep:aes-gcm", "dep:getrandom"] @@ -51,7 +75,6 @@ dirs = { version = "6.0", optional = true } getrandom = { version = "0.4.3", optional = true } hex = "0.4" postcard = { version = "1", default-features = false, features = ["use-std"], optional = true } -rpassword = "7.5.4" rusqlite = { version = "0.40.1", default-features = false, optional = true } serde = { version = "1", optional = true } sha2 = { version = "0.11", optional = true } @@ -66,6 +89,49 @@ zeroize = { version = "1.9.0", features = ["zeroize_derive"] } [dev-dependencies] criterion = { version = "0.8", features = ["html_reports"] } +[target.'cfg(not(target_family = "wasm"))'.dependencies] +rpassword = "7.5.4" + +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] +getrandom = { version = "0.4.3", features = ["wasm_js"], optional = true } +js-sys = { version = "0.3", optional = true } +wasm-bindgen = { version = "0.2.130", optional = true } +wasm-bindgen-futures = { version = "0.4", optional = true } +web-sys = { version = "0.3", optional = true, features = [ + "Window", + "Storage", + "Performance", + "WorkerGlobalScope", + "WorkerNavigator", + "StorageManager", + "LockManager", + "LockManagerSnapshot", + "Lock", + "IdbFactory", + "IdbDatabase", + "IdbOpenDbRequest", + "IdbObjectStore", + "IdbTransaction", + "IdbTransactionMode", + "IdbRequest", + "FileSystemDirectoryHandle", + "FileSystemFileHandle", + "FileSystemGetFileOptions", + "FileSystemSyncAccessHandle", + "FileSystemReadWriteOptions", +] } + +# Turso's native page encryption on wasm must use its pure-Rust ciphers; +# the native `aegis` build links C. +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies.turso] +version = "=0.9.0-pre.1" +default-features = false +features = ["pure-rust-crypto"] +optional = true + +[target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dev-dependencies] +wasm-bindgen-test = "0.3" + [[bench]] name = "cipher_bench" harness = false diff --git a/src/keyring.rs b/src/keyring.rs index a238a09..c68ddc1 100644 --- a/src/keyring.rs +++ b/src/keyring.rs @@ -3,6 +3,13 @@ SPDX-License-Identifier: Apache-2.0 */ +#[cfg(any( + feature = "encrypted-vfs", + feature = "memory", + feature = "turso-encrypted-io" +))] +mod cipher; + mod keyringsecret; #[cfg(feature = "encrypted-vfs")] @@ -10,6 +17,7 @@ pub mod encrypted_vfs; #[cfg(any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ))] @@ -20,6 +28,8 @@ pub mod kms; pub mod linux; #[cfg(all(target_os = "macos", feature = "macos-keychain"))] pub mod macos; +#[cfg(feature = "memory")] +pub mod memory; #[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))] mod page_cipher; #[cfg(feature = "file")] @@ -99,6 +109,7 @@ pub fn get_os_keyring(service: &str) -> Result> { all(target_os = "linux", feature = "linux-secret-service"), feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io", feature = "yubihsm-usb", @@ -106,6 +117,38 @@ pub fn get_os_keyring(service: &str) -> Result> { )))] compile_error!("no keyring implementation is selected or available for this platform"); +// Backends that need native OS APIs, C libraries or USB devices. They are +// rejected on wasm targets so the build fails with a clear message instead of +// a wall of linker errors. +#[cfg(all( + target_family = "wasm", + any( + feature = "file", + feature = "encrypted-vfs", + feature = "yubihsm-usb", + feature = "yubihsm-http", + feature = "linux-secret-service", + feature = "macos-keychain", + feature = "windows-credentials", + ) +))] +compile_error!( + "the file, encrypted-vfs, yubihsm and OS keyring backends are not available on wasm; \ + use the memory, web-storage, indexeddb, opfs or turso features instead" +); + +// Browser-only features asked for by a non-browser target. +#[cfg(all( + not(all(target_arch = "wasm32", target_os = "unknown")), + any( + feature = "web-storage", + feature = "indexeddb", + feature = "opfs", + feature = "js" + ) +))] +compile_error!("the web-storage, indexeddb, opfs and js features require wasm32-unknown-unknown"); + #[cfg(any( all(target_os = "linux", feature = "linux-secret-service"), all(target_os = "macos", feature = "macos-keychain"), @@ -144,6 +187,7 @@ pub const fn allows_file() -> bool { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -158,6 +202,7 @@ pub const fn default_memory_cost() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -172,6 +217,7 @@ pub const fn default_memory_cost() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -186,6 +232,7 @@ pub const fn default_threads() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -200,6 +247,7 @@ pub const fn default_threads() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -214,6 +262,7 @@ pub const fn default_parallel() -> u32 { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) @@ -275,6 +324,7 @@ pub trait ListKeyRing { any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ) diff --git a/src/keyring/cipher.rs b/src/keyring/cipher.rs new file mode 100644 index 0000000..b9e7e9a --- /dev/null +++ b/src/keyring/cipher.rs @@ -0,0 +1,45 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! The AEAD algorithm choice shared by every encrypted keyring. + +use super::file_common; +use crate::Result; +use crate::error::KeyRingError; +use zeroize::Zeroize; + +/// Selects the AEAD algorithm used for page encryption. +/// +/// `Aes256Gcm` uses AES-NI hardware acceleration on x86/x86_64/AArch64 when +/// available; on hardware without AES-NI it falls back to a constant-time +/// software implementation that is slower than ChaCha20-Poly1305. +#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] +pub enum CipherAlgorithm { + /// ChaCha20-Poly1305 (default) + #[default] + ChaCha20Poly1305, + /// AES-256-GCM + Aes256Gcm, +} + +impl Zeroize for CipherAlgorithm { + fn zeroize(&mut self) { + *self = CipherAlgorithm::default(); + } +} + +impl file_common::CipherParam for CipherAlgorithm { + fn parse(value: &str) -> Result { + match value { + "chacha20poly1305" | "chacha20" => Ok(CipherAlgorithm::ChaCha20Poly1305), + "aes256gcm" | "aes" => Ok(CipherAlgorithm::Aes256Gcm), + other => Err(KeyRingError::GeneralError { + msg: format!( + "unknown cipher '{}'; use chacha20poly1305 or aes256gcm", + other + ), + }), + } + } +} diff --git a/src/keyring/encrypted_vfs.rs b/src/keyring/encrypted_vfs.rs index a5d9651..97844fa 100644 --- a/src/keyring/encrypted_vfs.rs +++ b/src/keyring/encrypted_vfs.rs @@ -20,7 +20,7 @@ use super::page_cipher::{ActiveCipher, LOGICAL_PAGE_SIZE, logical_size, truncate use super::sqlite_common::{KEYRING_FILE, init_schema, lock_connection}; use crate::error::KeyRingError; -pub use super::page_cipher::CipherAlgorithm; +pub use super::cipher::CipherAlgorithm; /// Connection parameters for [`EncryptedVfsKeyring`]. /// diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 233adaa..1787f2e 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -9,27 +9,76 @@ use super::*; use argon2::{Algorithm, Argon2, Params as Argon2Params, Version}; use crate::error::KeyRingError; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] +use std::fs; #[cfg(any( feature = "encrypted-vfs", feature = "turso", feature = "turso-encrypted-io" ))] use std::fs::{File, OpenOptions, TryLockError}; +use std::iter; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] use std::path::{Path, PathBuf}; use std::str::FromStr; -use std::{fs, iter}; use zeroize::{Zeroize, Zeroizing}; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] // SQL shared by every file-backed keyring. Numbered parameters and // `excluded.value` work with both SQLite and Turso. pub(crate) const VERIFY_KEY_SQL: &str = "SELECT COUNT(*) FROM sqlite_master"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const CREATE_SECRETS_SQL: &str = "CREATE TABLE IF NOT EXISTS secrets (id TEXT UNIQUE NOT NULL, value TEXT NOT NULL)"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const SELECT_SECRET_SQL: &str = "SELECT value FROM secrets WHERE id = ?1"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const UPSERT_SECRET_SQL: &str = "INSERT INTO secrets(id, value) VALUES(?1, ?2) \ ON CONFLICT(id) DO UPDATE SET value = excluded.value"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] pub(crate) const DELETE_SECRET_SQL: &str = "DELETE FROM secrets WHERE id = ?1"; +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" +))] /// Storage behind a file-backed keyring. Secrets are stored hex-encoded. pub(crate) trait SecretStore { /// Fetch the secret stored under `id`. @@ -40,6 +89,12 @@ pub(crate) trait SecretStore { fn delete(&self, id: &str) -> Result<()>; } +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", +))] /// Decode a stored hex value, or report [`KeyRingError::ItemNotFound`]. pub(crate) fn decode_secret(value: Option>) -> Result { let value = value.ok_or(KeyRingError::ItemNotFound)?; @@ -50,6 +105,12 @@ pub(crate) fn decode_secret(value: Option>) -> Result KeyRingError { KeyRingError::AccessDenied { @@ -60,6 +121,7 @@ pub(crate) fn invalid_key() -> KeyRingError { /// Implements [`DynKeyRing`] by delegating to the [`SecretStore`] in field /// `$store`, and [`NewKeyRing`] by parsing the calling module's /// `ConnectionParams` and calling `with_params(¶ms, None)`. +#[allow(unused_macros)] macro_rules! file_keyring { ($keyring:ty, $store:ident) => { impl $crate::DynKeyRing for $keyring { @@ -84,6 +146,15 @@ macro_rules! file_keyring { } }; } +// Only the backends that own a `SecretStore` use the macro. +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", + feature = "yubihsm-usb", + feature = "yubihsm-http" +))] pub(crate) use file_keyring; /// A cipher choice that can be set with `cipher=` in a connection string. @@ -302,6 +373,7 @@ pub(crate) fn derive_key( /// Derive a key with [`derive_key`] and require it to be exactly 32 bytes. #[cfg(any( feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ))] @@ -319,6 +391,12 @@ pub(crate) fn derive_key_32( Ok(out) } +#[cfg(any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", +))] /// Resolve the keyring file `file_name` inside `in_path` (default /// `~/.cryptex`), creating and securing the directory. pub(crate) fn get_keyring_file(in_path: Option, file_name: &str) -> Result { @@ -433,7 +511,15 @@ pub(crate) fn sibling_path(path: &Path, suffix: &str) -> PathBuf { PathBuf::from(s) } -#[cfg(unix)] +#[cfg(all( + unix, + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn secure_dir(path: &Path) -> Result<()> { use std::os::unix::fs::PermissionsExt; @@ -444,7 +530,15 @@ fn secure_dir(path: &Path) -> Result<()> { }) } -#[cfg(not(unix))] +#[cfg(all( + not(unix), + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn secure_dir(_path: &Path) -> Result<()> { Ok(()) } @@ -467,7 +561,15 @@ pub(crate) fn secure_file(_path: &Path) -> Result<()> { Ok(()) } -#[cfg(target_os = "windows")] +#[cfg(all( + target_os = "windows", + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn make_hidden(path: &Path) { use std::ffi::OsStr; use std::os::windows::ffi::OsStrExt; @@ -491,7 +593,15 @@ fn make_hidden(path: &Path) { } } -#[cfg(not(target_os = "windows"))] +#[cfg(all( + not(target_os = "windows"), + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] fn make_hidden(_path: &Path) {} struct Parser<'a> { @@ -644,7 +754,15 @@ impl<'a> Parser<'a> { } /// Helpers shared by the file-backed keyring tests. -#[cfg(test)] +#[cfg(all( + test, + any( + feature = "file", + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io" + ) +))] pub(crate) mod test_support { use std::ops::Deref; use std::path::{Path, PathBuf}; diff --git a/src/keyring/memory.rs b/src/keyring/memory.rs new file mode 100644 index 0000000..f231f05 --- /dev/null +++ b/src/keyring/memory.rs @@ -0,0 +1,564 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! An encrypted, in-memory keyring. +//! +//! [`MemoryKeyring`] keeps every secret in a [`BTreeMap`] and never touches the +//! disk, so it builds for every target, including browsers and WASI. Secrets +//! only leave memory through [`MemoryKeyring::export`], which returns a single +//! AEAD-sealed blob, and return through [`MemoryKeyring::import`]. +//! +//! ``` +//! use cryptex::KeyRing; +//! use cryptex::memory::MemoryKeyring; +//! +//! let params: cryptex::memory::ConnectionParams = +//! "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv".parse().unwrap(); +//! let mut keyring = MemoryKeyring::with_params(¶ms).unwrap(); +//! keyring.set_secret("token", b"secret value").unwrap(); +//! +//! // Persist the sealed blob wherever you like, then reopen it later. +//! let blob = keyring.export().unwrap(); +//! // Reopening needs the same password (or raw key); the salt, cipher and +//! // Argon2 parameters come from the blob itself. +//! let mut reopened = +//! MemoryKeyring::import(&blob, b"1qaz2wsx3edc4rfv").unwrap(); +//! assert_eq!(reopened.get_secret("token").unwrap().as_slice(), b"secret value"); +//! ``` + +use super::cipher::CipherAlgorithm; +use super::file_common::{self, derive_key_32}; +use super::*; +use crate::error::KeyRingError; +use aes_gcm::aead::{Aead, KeyInit}; +use std::collections::BTreeMap; +use zeroize::Zeroizing; + +/// Connection parameters for [`MemoryKeyring`]. +/// +/// Accepted format: +/// ```text +/// password=mysecret salt=0okm9ijn8uhb7ygv [cipher=chacha20poly1305|aes256gcm] +/// ``` +/// or, to supply the 32-byte key directly, `key=`. +pub type ConnectionParams = file_common::ConnectionParams; + +// Sealed blob layout. The whole header is the AEAD associated data, so the +// Argon2 parameters, salt and cipher travel with the blob and cannot be +// altered without failing the tag check. +// +// magic(8) | version(1) | kind(1) | cipher(1) | memory(4) | threads(4) | +// parallel(4) | salt_len(4) | salt(salt_len) | nonce(12) | ciphertext + tag +const BLOB_MAGIC: &[u8; 8] = b"CRYPTEX\0"; +const BLOB_VERSION: u8 = 1; +const HEADER_LEN: usize = 8 + 1 + 1 + 1 + 4 + 4 + 4 + 4; +const NONCE_SIZE: usize = 12; + +/// How the blob's key was produced. +mod kind { + /// Argon2id over password + salt. + pub(super) const PASSWORD: u8 = 1; + /// A caller-supplied 32-byte key. + pub(super) const RAW_KEY: u8 = 2; +} + +fn seal_cipher(cipher: CipherAlgorithm) -> u8 { + match cipher { + CipherAlgorithm::ChaCha20Poly1305 => 1, + CipherAlgorithm::Aes256Gcm => 2, + } +} + +fn open_cipher(tag: u8) -> Result { + match tag { + 1 => Ok(CipherAlgorithm::ChaCha20Poly1305), + 2 => Ok(CipherAlgorithm::Aes256Gcm), + other => Err(KeyRingError::GeneralError { + msg: format!("unsupported cipher in keyring blob: {}", other), + }), + } +} + +/// The error for a blob that will not open: wrong password or tampering. +fn invalid_blob() -> KeyRingError { + KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring blob".to_string(), + } +} + +/// Authenticated encryption over a whole buffer, for either supported cipher. +enum Sealer { + ChaCha(Box), + Aes(Box), +} + +impl Sealer { + fn new(cipher: CipherAlgorithm, key: &[u8; 32]) -> Self { + match cipher { + CipherAlgorithm::ChaCha20Poly1305 => Self::ChaCha(Box::new( + chacha20poly1305::ChaCha20Poly1305::new_from_slice(key).expect("32-byte key"), + )), + CipherAlgorithm::Aes256Gcm => Self::Aes(Box::new( + aes_gcm::Aes256Gcm::new_from_slice(key).expect("32-byte key"), + )), + } + } + + fn nonce(bytes: &[u8]) -> Option { + chacha20poly1305::Nonce::try_from(bytes).ok() + } + + fn seal(&self, nonce: &[u8; NONCE_SIZE], aad: &[u8], plaintext: &[u8]) -> Option> { + let nonce = Self::nonce(nonce)?; + let payload = chacha20poly1305::aead::Payload { + msg: plaintext, + aad, + }; + match self { + Self::ChaCha(c) => c.encrypt(&nonce, payload).ok(), + Self::Aes(c) => c.encrypt(&nonce, payload).ok(), + } + } + + fn open(&self, nonce: &[u8], aad: &[u8], ciphertext: &[u8]) -> Option> { + let nonce = Self::nonce(nonce)?; + let payload = chacha20poly1305::aead::Payload { + msg: ciphertext, + aad, + }; + match self { + Self::ChaCha(c) => c.decrypt(&nonce, payload).ok(), + Self::Aes(c) => c.decrypt(&nonce, payload).ok(), + } + } +} + +/// Length-prefixed encoding of the secret table: +/// `count(u32) | [id_len(u32) id value_len(u32) value]*`. +fn encode_secrets(secrets: &BTreeMap>>) -> Result> { + let too_long = |what: &str| KeyRingError::GeneralError { + msg: format!("{} is too large to export", what), + }; + let mut out = u32::try_from(secrets.len()) + .map_err(|_| too_long("the secret count"))? + .to_le_bytes() + .to_vec(); + for (id, value) in secrets { + let id_len = u32::try_from(id.len()).map_err(|_| too_long("a secret id"))?; + let value_len = u32::try_from(value.len()).map_err(|_| too_long("a secret value"))?; + out.extend_from_slice(&id_len.to_le_bytes()); + out.extend_from_slice(id.as_bytes()); + out.extend_from_slice(&value_len.to_le_bytes()); + out.extend_from_slice(value); + } + Ok(out) +} + +/// Read a `u32` at `pos`, advancing past it. +fn read_u32(data: &[u8], pos: &mut usize) -> Option { + let mut raw = [0u8; 4]; + raw.copy_from_slice(data.get(*pos..*pos + 4)?); + *pos += 4; + Some(u32::from_le_bytes(raw)) +} + +/// Decode the plaintext table produced by [`encode_secrets`], rejecting any +/// trailing bytes. +fn decode_secrets(data: &[u8]) -> Option>>> { + let mut pos = 0usize; + let count = read_u32(data, &mut pos)? as usize; + let mut secrets = BTreeMap::new(); + for _ in 0..count { + let id_len = read_u32(data, &mut pos)? as usize; + let id = std::str::from_utf8(data.get(pos..pos.checked_add(id_len)?)?) + .ok()? + .to_string(); + pos += id_len; + let value_len = read_u32(data, &mut pos)? as usize; + let value = Zeroizing::new(data.get(pos..pos.checked_add(value_len)?)?.to_vec()); + pos += value_len; + secrets.insert(id, value); + } + (pos == data.len()).then_some(secrets) +} + +/// Header fields of a sealed blob. +struct Header<'a> { + kind: u8, + cipher: CipherAlgorithm, + memory: u32, + threads: u32, + parallel: u32, + salt: &'a [u8], +} + +/// A keyring that keeps its secrets in memory. +/// +/// The key is derived once from the connection parameters and zeroized on +/// drop; [`export`](Self::export) seals everything under a fresh nonce. +pub struct MemoryKeyring { + secrets: BTreeMap>>, + key: Zeroizing<[u8; 32]>, + cipher: CipherAlgorithm, + kind: u8, + salt: Vec, + memory: u32, + threads: u32, + parallel: u32, +} + +impl MemoryKeyring { + /// Open an empty keyring from the connection parameters. + pub fn with_params(params: &ConnectionParams) -> Result { + let kind = if params.key.is_empty() { + kind::PASSWORD + } else { + kind::RAW_KEY + }; + Ok(Self { + secrets: BTreeMap::new(), + key: derive_key_32(params)?, + cipher: params.cipher, + kind, + salt: params.salt.clone(), + memory: params.memory, + threads: params.threads, + parallel: params.parallel, + }) + } + + /// Reopen a keyring from a blob returned by [`export`](Self::export). + /// + /// A blob made from a password derives its key from the salt and Argon2 + /// parameters stored in the blob, so it needs only the same password. A + /// blob made from a raw key needs the same key. + /// + /// A wrong password or a modified blob returns + /// [`KeyRingError::AccessDenied`]. + pub fn import(blob: &[u8], password_or_key: &[u8]) -> Result { + let header = Self::parse_header(blob)?; + let params = ConnectionParams { + key: if header.kind == kind::RAW_KEY { + password_or_key.to_vec() + } else { + Vec::new() + }, + password: if header.kind == kind::RAW_KEY { + Vec::new() + } else { + password_or_key.to_vec() + }, + salt: header.salt.to_vec(), + memory: header.memory, + threads: header.threads, + parallel: header.parallel, + cipher: header.cipher, + }; + let key = derive_key_32(¶ms).map_err(|_| invalid_blob())?; + let aad_end = HEADER_LEN + header.salt.len(); + let body = &blob[aad_end..]; + let sealer = Sealer::new(header.cipher, &key); + let plaintext = Zeroizing::new( + sealer + .open(&body[..NONCE_SIZE], &blob[..aad_end], &body[NONCE_SIZE..]) + .ok_or_else(invalid_blob)?, + ); + let secrets = decode_secrets(&plaintext).ok_or_else(invalid_blob)?; + Ok(Self { + secrets, + key, + cipher: header.cipher, + kind: header.kind, + salt: header.salt.to_vec(), + memory: header.memory, + threads: header.threads, + parallel: header.parallel, + }) + } + + fn parse_header(blob: &[u8]) -> Result> { + if blob.len() < HEADER_LEN + NONCE_SIZE { + return Err(invalid_blob()); + } + if blob.get(..8) != Some(BLOB_MAGIC.as_slice()) { + return Err(invalid_blob()); + } + if blob[8] != BLOB_VERSION { + return Err(KeyRingError::GeneralError { + msg: format!("unsupported keyring blob version: {}", blob[8]), + }); + } + let blob_kind = blob[9]; + if blob_kind != kind::PASSWORD && blob_kind != kind::RAW_KEY { + return Err(invalid_blob()); + } + let mut pos = 11; + let memory = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; + let threads = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; + let parallel = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; + let salt_len = read_u32(blob, &mut pos).ok_or_else(invalid_blob)? as usize; + let salt = blob + .get(HEADER_LEN..HEADER_LEN + salt_len) + .ok_or_else(invalid_blob)?; + // The body must hold a nonce and at least the AEAD tag. + if salt_len.checked_add(HEADER_LEN + NONCE_SIZE + 16) > Some(blob.len()) { + return Err(invalid_blob()); + } + Ok(Header { + kind: blob_kind, + cipher: open_cipher(blob[10]).map_err(|_| invalid_blob())?, + memory, + threads, + parallel, + salt, + }) + } + + /// Seal every secret into a single AEAD blob. + /// + /// The blob carries the salt, Argon2 parameters, cipher and key kind, so + /// [`import`](Self::import) needs only the same password (or raw key). + pub fn export(&self) -> Result> { + let mut nonce = [0u8; NONCE_SIZE]; + getrandom::fill(&mut nonce).map_err(|e| KeyRingError::GeneralError { + msg: format!("unable to generate a nonce: {}", e), + })?; + + let plaintext = Zeroizing::new(encode_secrets(&self.secrets)?); + let salt_len = u32::try_from(self.salt.len()).map_err(|_| KeyRingError::GeneralError { + msg: "salt is too long to export".to_string(), + })?; + let mut header = Vec::with_capacity(HEADER_LEN + self.salt.len()); + header.extend_from_slice(BLOB_MAGIC); + header.push(BLOB_VERSION); + header.push(self.kind); + header.push(seal_cipher(self.cipher)); + header.extend_from_slice(&self.memory.to_le_bytes()); + header.extend_from_slice(&self.threads.to_le_bytes()); + header.extend_from_slice(&self.parallel.to_le_bytes()); + header.extend_from_slice(&salt_len.to_le_bytes()); + header.extend_from_slice(&self.salt); + + let ciphertext = Sealer::new(self.cipher, &self.key) + .seal(&nonce, &header, &plaintext) + .ok_or_else(|| KeyRingError::GeneralError { + msg: "unable to encrypt the keyring".to_string(), + })?; + let mut blob = header; + blob.extend_from_slice(&nonce); + blob.extend_from_slice(&ciphertext); + Ok(blob) + } + + /// Re-encrypt under new connection parameters, optionally with a new cipher. + /// + /// The secrets stay in memory; only the key, salt and cipher change, so + /// the next [`export`](Self::export) uses the new parameters. + pub fn rekey(&mut self, new_params: &ConnectionParams) -> Result<()> { + let key = derive_key_32(new_params)?; + self.kind = if new_params.key.is_empty() { + kind::PASSWORD + } else { + kind::RAW_KEY + }; + self.salt = new_params.salt.clone(); + self.memory = new_params.memory; + self.threads = new_params.threads; + self.parallel = new_params.parallel; + self.cipher = new_params.cipher; + self.key = key; + Ok(()) + } + + /// The cipher this keyring seals blobs with. + pub fn cipher(&self) -> CipherAlgorithm { + self.cipher + } +} + +impl NewKeyRing for MemoryKeyring { + fn new>(lock_key: S) -> Result { + let params = lock_key.as_ref().parse::()?; + Self::with_params(¶ms) + } +} + +impl DynKeyRing for MemoryKeyring { + fn get_secret(&mut self, id: &str) -> Result { + match self.secrets.get(id) { + Some(value) => Ok(KeyRingSecret(value.to_vec())), + None => Err(KeyRingError::ItemNotFound), + } + } + + fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> { + self.secrets + .insert(id.to_string(), Zeroizing::new(secret.to_vec())); + Ok(()) + } + + fn delete_secret(&mut self, id: &str) -> Result<()> { + match self.secrets.remove(id) { + Some(mut value) => { + zeroize::Zeroize::zeroize(&mut *value); + Ok(()) + } + None => Err(KeyRingError::ItemNotFound), + } + } +} + +#[cfg(test)] +mod tests { + // Only `DynKeyRing` is imported, so `kr.get_secret(..)` is unambiguous. + use super::super::DynKeyRing; + use super::{CipherAlgorithm, ConnectionParams, HEADER_LEN, MemoryKeyring}; + use crate::error::KeyRingError; + + const PASSWORD: &[u8] = b"1qaz2wsx3edc4rfv"; + + fn params(s: &str) -> ConnectionParams { + s.parse().unwrap() + } + + fn password_params(extra: &str) -> ConnectionParams { + params(&format!( + "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv {extra}" + )) + } + + #[test] + fn round_trip_and_persistence() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("a", b"one").unwrap(); + kr.set_secret("b", b"two").unwrap(); + kr.delete_secret("b").unwrap(); + assert_eq!(kr.get_secret("a").unwrap().as_slice(), b"one"); + assert!(matches!( + kr.get_secret("b"), + Err(KeyRingError::ItemNotFound) + )); + + let blob = kr.export().unwrap(); + let mut reopened = MemoryKeyring::import(&blob, PASSWORD).unwrap(); + assert_eq!(reopened.get_secret("a").unwrap().as_slice(), b"one"); + reopened.set_secret("c", b"three").unwrap(); + assert_eq!(reopened.get_secret("c").unwrap().as_slice(), b"three"); + } + + #[test] + fn empty_keyring_round_trips() { + let kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + let blob = kr.export().unwrap(); + let mut reopened = MemoryKeyring::import(&blob, PASSWORD).unwrap(); + assert!(matches!( + reopened.get_secret("missing"), + Err(KeyRingError::ItemNotFound) + )); + } + + #[test] + fn wrong_password_is_denied() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("a", b"one").unwrap(); + let blob = kr.export().unwrap(); + assert!(matches!( + MemoryKeyring::import(&blob, b"wrong"), + Err(KeyRingError::AccessDenied { .. }) + )); + } + + #[test] + fn tampering_is_detected() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("a", b"one").unwrap(); + let blob = kr.export().unwrap(); + + // Header, salt and body are all authenticated. + for index in [9usize, 10, 12, HEADER_LEN + 1, blob.len() - 1] { + let mut flipped = blob.clone(); + flipped[index] ^= 0x80; + assert!( + MemoryKeyring::import(&flipped, PASSWORD).is_err(), + "flipping byte {} went undetected", + index + ); + } + + assert!(MemoryKeyring::import(&blob[..blob.len() - 1], PASSWORD).is_err()); + assert!(MemoryKeyring::import(b"", PASSWORD).is_err()); + } + + #[test] + fn both_ciphers_and_rekey() { + for (cipher, other) in [ + ("chacha20poly1305", "aes256gcm"), + ("aes256gcm", "chacha20poly1305"), + ] { + let mut kr = + MemoryKeyring::with_params(&password_params(&format!("cipher={cipher}"))).unwrap(); + kr.set_secret("a", b"one").unwrap(); + let mut reopened = MemoryKeyring::import(&kr.export().unwrap(), PASSWORD).unwrap(); + assert_eq!(reopened.get_secret("a").unwrap().as_slice(), b"one"); + + reopened + .rekey(¶ms(&format!( + "password=new_password salt=another_salt_value cipher={other}" + ))) + .unwrap(); + assert_eq!( + reopened.cipher(), + if other == "aes256gcm" { + CipherAlgorithm::Aes256Gcm + } else { + CipherAlgorithm::ChaCha20Poly1305 + } + ); + + let rekeyed = reopened.export().unwrap(); + assert!(MemoryKeyring::import(&rekeyed, PASSWORD).is_err()); + let mut again = MemoryKeyring::import(&rekeyed, b"new_password").unwrap(); + assert_eq!(again.get_secret("a").unwrap().as_slice(), b"one"); + } + } + + #[test] + fn raw_key_blobs_need_the_key() { + let key = "0f1e2d3c4b5a69788796a5b4c3d2e1f00f1e2d3c4b5a69788796a5b4c3d2e1f0"; + let mut kr = + MemoryKeyring::with_params(¶ms(&format!("key={} salt=ignored_salt_value", key))) + .unwrap(); + kr.set_secret("a", b"one").unwrap(); + let blob = kr.export().unwrap(); + + let key_bytes = hex::decode(key).unwrap(); + let mut reopened = MemoryKeyring::import(&blob, &key_bytes).unwrap(); + assert_eq!(reopened.get_secret("a").unwrap().as_slice(), b"one"); + assert!(MemoryKeyring::import(&blob, PASSWORD).is_err()); + + // A raw-key blob carries no password, so the password path must fail. + assert!(MemoryKeyring::import(&blob, b"anything").is_err()); + } + + #[test] + fn blobs_carry_no_plaintext() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("account", b"super-secret-value").unwrap(); + let blob = kr.export().unwrap(); + assert!(!blob.windows(18).any(|w| w == b"super-secret-value")); + assert!(!blob.windows(7).any(|w| w == b"account")); + } + + #[test] + fn ids_and_values_survive_odd_characters() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + kr.set_secret("ünïcode/ключ", b"\x00\x01\x02bytes").unwrap(); + let blob = kr.export().unwrap(); + let mut reopened = MemoryKeyring::import(&blob, PASSWORD).unwrap(); + assert_eq!( + reopened.get_secret("ünïcode/ключ").unwrap().as_slice(), + b"\x00\x01\x02bytes" + ); + } +} diff --git a/src/keyring/page_cipher.rs b/src/keyring/page_cipher.rs index 840971a..70d1b96 100644 --- a/src/keyring/page_cipher.rs +++ b/src/keyring/page_cipher.rs @@ -9,7 +9,7 @@ //! `[ciphertext(4096) | nonce(12) | tag(16)]`, with the page number bound as //! associated data so pages cannot be swapped. -use super::*; +use super::cipher::CipherAlgorithm; use aes_gcm::Aes256Gcm; use chacha20poly1305::{ ChaCha20Poly1305, @@ -18,9 +18,6 @@ use chacha20poly1305::{ use std::fs::File; use std::io::{self, Read, Seek, SeekFrom, Write}; use std::iter; -use zeroize::Zeroize; - -use crate::error::KeyRingError; pub(crate) const LOGICAL_PAGE_SIZE: usize = 4096; const NONCE_SIZE: usize = 12; @@ -28,41 +25,6 @@ const TAG_SIZE: usize = 16; /// Physical block on disk = [ciphertext(4096) | nonce(12) | tag(16)] pub(crate) const PHYSICAL_PAGE_SIZE: usize = LOGICAL_PAGE_SIZE + NONCE_SIZE + TAG_SIZE; // 4124 -/// Selects the AEAD algorithm used for page encryption. -/// -/// `Aes256Gcm` uses AES-NI hardware acceleration on x86/x86_64/AArch64 when -/// available; on hardware without AES-NI it falls back to a constant-time -/// software implementation that is slower than ChaCha20-Poly1305. -#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)] -pub enum CipherAlgorithm { - /// ChaCha20-Poly1305 (default) - #[default] - ChaCha20Poly1305, - /// AES-256-GCM - Aes256Gcm, -} - -impl Zeroize for CipherAlgorithm { - fn zeroize(&mut self) { - *self = CipherAlgorithm::default(); - } -} - -impl file_common::CipherParam for CipherAlgorithm { - fn parse(value: &str) -> Result { - match value { - "chacha20poly1305" | "chacha20" => Ok(CipherAlgorithm::ChaCha20Poly1305), - "aes256gcm" | "aes" => Ok(CipherAlgorithm::Aes256Gcm), - other => Err(KeyRingError::GeneralError { - msg: format!( - "unknown cipher '{}'; use chacha20poly1305 or aes256gcm", - other - ), - }), - } - } -} - // Internal dispatch — one variant per algorithm. Both use 12-byte nonces and // 16-byte tags so the physical page layout is identical regardless of choice. pub(crate) enum ActiveCipher { diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 7276a4e..a53e3e5 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -11,6 +11,7 @@ use super::*; use ::turso::{Builder, EncryptionOpts}; use std::path::PathBuf; +use std::sync::Arc; use zeroize::{Zeroize, Zeroizing}; use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_file}; @@ -62,11 +63,29 @@ impl CipherParam for TursoCipher { /// ``` pub type ConnectionParams = file_common::ConnectionParams; +/// Turso's builder, re-exported so callers construct matching types. +pub use ::turso::Builder as TursoBuilder; +/// The Turso connection type a keyring can adopt. +/// +/// Use the `turso` crate cryptex was built against (the same version as +/// [`Builder`]), or a type mismatch will result. +pub use ::turso::Connection; +/// Turso's low-level crate, for implementing a custom `IO` such as OPFS. +pub use ::turso::core; + /// A keyring stored in a Turso database encrypted with Turso's native page /// encryption. The default file is `~/.cryptex/keyring-turso.db3`. /// /// Turso keeps its own copy of the hex-encoded key for the life of the /// database; cryptex zeroizes only the copies it owns. +/// +/// Three ways to get one: +/// - [`with_params`](Self::with_params) opens the file itself, as before. +/// - [`from_connection`](Self::from_connection) adopts a connection the caller +/// already opened, so key storage and application tables can share one +/// database and one key. +/// - [`with_io`](Self::with_io) opens through a caller-supplied Turso `IO`, +/// such as the Origin Private File System in a browser worker. pub struct TursoKeyring { file: TursoFile, } @@ -77,10 +96,57 @@ impl TursoKeyring { /// Open (or create) the keyring in `path` (default `~/.cryptex`). pub fn with_params(connection: &ConnectionParams, path: Option) -> Result { let file = TursoFile::open(path, builder(connection)?)?; - secure_file(file.db_path())?; + if let Some(db_path) = file.db_path() { + secure_file(db_path)?; + } Ok(Self { file }) } + /// Adopt an already-open Turso connection. + /// + /// The keyring creates and owns its `secrets` table and uses the + /// connection as given, so an application can keep its own tables in the + /// same database and share one key derivation. Nothing about the + /// connection is reconfigured: encryption, IO and the clock are the + /// caller's. + /// + /// The caller is responsible for opening the database with the right key + /// and, in a browser, for holding the single-writer storage handle. + /// + /// [`rekey`](Self::rekey) is not available on an adopted keyring because + /// cryptex does not own the storage; copy the secrets into a new keyring + /// instead. + /// + /// ```no_run + /// # use cryptex::turso::{TursoKeyring, TursoBuilder}; + /// # async fn example(conn: cryptex::turso::Connection) -> Result<(), Box> { + /// // The caller opened the database, e.g. with its own IO and encryption. + /// let mut keyring = TursoKeyring::from_connection(conn)?; + /// # Ok(()) + /// # } + /// ``` + pub fn from_connection(conn: Connection) -> Result { + Ok(Self { + file: TursoFile::adopt(conn)?, + }) + } + + /// Open (or create) the keyring through a caller-supplied Turso `IO`. + /// + /// `io` supplies every page: for example an OPFS-backed `IO` in a browser + /// worker. `path` is the database path passed to that IO. The key is + /// derived from `params` and applied with Turso's native page encryption, + /// exactly as [`with_params`](Self::with_params) does. + /// + /// No lock file is created and [`rekey`](Self::rekey) is unavailable; the + /// caller owns single-writer access, which for OPFS means holding the one + /// sync access handle for the database. + pub fn with_io(io: Arc, path: &str, params: &ConnectionParams) -> Result { + Ok(Self { + file: TursoFile::open_with(builder(params)?(path).with_io_impl(io))?, + }) + } + /// Re-encrypt the keyring with a new key (and optionally a different cipher). /// /// Consumes the keyring and returns it reopened under `new_params`. If @@ -88,7 +154,9 @@ impl TursoKeyring { /// with the old parameters. pub fn rekey(self, new_params: &ConnectionParams) -> Result { let file = self.file.rekey(builder(new_params)?)?; - secure_file(file.db_path())?; + if let Some(db_path) = file.db_path() { + secure_file(db_path)?; + } Ok(Self { file }) } } @@ -113,7 +181,9 @@ mod tests { use crate::KeyRing; use crate::error::KeyRingError; use crate::file_common::test_support::TestDir; + use crate::keyring::turso_common::block_on; use std::fs; + use std::sync::Arc; fn params(s: &str) -> ConnectionParams { s.parse().unwrap() @@ -207,4 +277,97 @@ mod tests { assert!(TursoKeyring::with_params(&old_params, dir.keyring_dir()).is_err()); } + + /// A connection opened by the caller, as a browser worker would. + fn caller_connection( + path: std::path::PathBuf, + params: &ConnectionParams, + ) -> ::turso::Connection { + let hexkey = hex::encode(*crate::file_common::derive_key_32(params).unwrap()); + let db = block_on::<_, _, KeyRingError>(async { + ::turso::Builder::new_local(path.to_str().unwrap()) + .experimental_encryption(true) + .with_encryption(::turso::EncryptionOpts { + cipher: params.cipher.as_turso_name().to_string(), + hexkey, + }) + .build() + .await + .map_err(|e| KeyRingError::GeneralError { msg: e.to_string() }) + }) + .unwrap(); + db.connect().unwrap() + } + + #[test] + fn adopts_an_existing_connection() { + let dir = TestDir::new(".test-turso-from-connection"); + let p = params("password=adopt_pass salt=1qaz2wsx3edc4rfv5tgb"); + fs::create_dir_all(&*dir).unwrap(); + let conn = caller_connection(dir.join("shared.db3"), &p); + + // The application owns its own table on the same connection. + block_on(conn.execute("CREATE TABLE audit (event TEXT NOT NULL)", ())).unwrap(); + + { + let mut kr = TursoKeyring::from_connection(conn.clone()).unwrap(); + kr.set_secret("k1", b"value1").unwrap(); + kr.set_secret("k2", b"value2").unwrap(); + assert_eq!(kr.get_secret("k1").unwrap().0, b"value1"); + kr.delete_secret("k2").unwrap(); + assert!(matches!( + kr.get_secret("k2"), + Err(KeyRingError::ItemNotFound) + )); + } + + // Reopening through another connection to the same file sees the data, + // and the application table survived. + let mut kr = + TursoKeyring::from_connection(caller_connection(dir.join("shared.db3"), &p)).unwrap(); + assert_eq!(kr.get_secret("k1").unwrap().0, b"value1"); + + let mut rows = block_on(conn.query( + "SELECT name FROM sqlite_master WHERE type = 'table' ORDER BY name", + (), + )) + .unwrap(); + let mut tables = Vec::new(); + while let Some(row) = block_on(rows.next()).unwrap() { + tables.push(row.get::(0).unwrap()); + } + assert_eq!(tables, vec!["audit", "secrets"]); + } + + #[test] + fn adopted_keyring_cannot_rekey() { + let dir = TestDir::new(".test-turso-adopt-rekey"); + let p = params("password=adopt_pass salt=1qaz2wsx3edc4rfv5tgb"); + fs::create_dir_all(&*dir).unwrap(); + let kr = + TursoKeyring::from_connection(caller_connection(dir.join("shared.db3"), &p)).unwrap(); + assert!(kr.rekey(&p).is_err()); + } + + #[test] + fn opens_through_a_custom_io() { + // A caller-supplied IO stands in for OPFS in a browser worker. + let io = Arc::new(::turso::core::MemoryIO::new()); + let p = params("password=io_pass salt=1qaz2wsx3edc4rfv5tgb"); + let db_name = "keyring.db3"; + + { + let mut kr = TursoKeyring::with_io(io.clone(), db_name, &p).unwrap(); + kr.set_secret("k1", b"value1").unwrap(); + } + + { + let mut kr = TursoKeyring::with_io(io.clone(), db_name, &p).unwrap(); + assert_eq!(kr.get_secret("k1").unwrap().0, b"value1"); + } + + // A different key on the same pages is refused. + let wrong = params("password=wrong_pass salt=1qaz2wsx3edc4rfv5tgb"); + assert!(TursoKeyring::with_io(io, db_name, &wrong).is_err()); + } } diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index 72f2610..fa8ac47 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -9,12 +9,14 @@ use super::*; use ::turso::{Builder, Connection, Database}; -use std::fs::{self, File}; +use std::fs; +use std::fs::File; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::pin; use std::sync::Arc; use std::task::{Context, Poll, Wake, Waker}; +#[cfg(not(target_family = "wasm"))] use std::thread::{self, Thread}; use super::file_common::{ @@ -29,8 +31,10 @@ use zeroize::Zeroizing; /// `keyring.db3` so the backends never try to open each other's files. pub(crate) const KEYRING_FILE: &str = "keyring-turso.db3"; +#[cfg(not(target_family = "wasm"))] struct ThreadWaker(Thread); +#[cfg(not(target_family = "wasm"))] impl Wake for ThreadWaker { fn wake(self: Arc) { self.0.unpark(); @@ -38,40 +42,99 @@ impl Wake for ThreadWaker { } /// Drive `fut` to completion on the current thread. -fn block_on(fut: F) -> F::Output { +/// +/// Turso's futures only return `Pending` when the IO is asynchronous. Native +/// builds can block, so they park the thread until woken. Wasm threads cannot +/// block, so a wasm build polls a bounded number of times and fails instead of +/// spinning forever when an IO backend never completes in place. +#[cfg(not(target_family = "wasm"))] +pub(crate) fn block_on(fut: F) -> Result +where + F: Future>, + E: Into, +{ let mut fut = pin!(fut); let waker = Waker::from(Arc::new(ThreadWaker(thread::current()))); let mut cx = Context::from_waker(&waker); loop { if let Poll::Ready(out) = fut.as_mut().poll(&mut cx) { - return out; + return out.map_err(Into::into); } thread::park(); } } +/// How many times a pending future is re-polled before giving up on wasm. +#[cfg(target_family = "wasm")] +const MAX_WASM_POLLS: usize = 1_000_000; + +#[cfg(target_family = "wasm")] +struct SpinWaker; + +#[cfg(target_family = "wasm")] +impl Wake for SpinWaker { + fn wake(self: Arc) {} +} + +#[cfg(target_family = "wasm")] +fn block_on(fut: F) -> Result +where + F: Future>, + E: Into, +{ + let mut fut = pin!(fut); + let waker = Waker::from(Arc::new(SpinWaker)); + let mut cx = Context::from_waker(&waker); + for _ in 0..MAX_WASM_POLLS { + if let Poll::Ready(out) = fut.as_mut().poll(&mut cx) { + return out.map_err(Into::into); + } + } + Err(KeyRingError::GeneralError { + msg: "turso did not complete synchronously: the IO backend must complete \ + reads in place on wasm" + .to_string(), + }) +} + /// An open Turso database holding the `secrets` table. struct TursoStore { conn: Connection, - _db: Database, + /// Kept alive for as long as the store; `None` when the caller supplied + /// the connection and owns the database handle themselves. + _db: Option, } impl TursoStore { + /// Create the keyring's tables on an open connection, verifying the key. + async fn prepare(conn: Connection, db: Option) -> Result { + let mut rows = conn + .query(VERIFY_KEY_SQL, ()) + .await + .map_err(|_| invalid_key())?; + rows.next().await.map_err(|_| invalid_key())?; + drop(rows); + conn.execute(CREATE_SECRETS_SQL, ()).await?; + Ok(Self { conn, _db: db }) + } + + /// Open the database described by `builder` and create the tables. fn open(builder: Builder) -> Result { - block_on(async { + block_on::<_, Self, KeyRingError>(async { let db = builder.build().await?; let conn = db.connect()?; - let mut rows = conn - .query(VERIFY_KEY_SQL, ()) - .await - .map_err(|_| invalid_key())?; - rows.next().await.map_err(|_| invalid_key())?; - drop(rows); - conn.execute(CREATE_SECRETS_SQL, ()).await?; - Ok(Self { conn, _db: db }) + Self::prepare(conn, Some(db)).await }) } + /// Adopt an already-open connection. + /// + /// The keyring creates and owns its `secrets` table; everything else on + /// the connection is left alone, so application tables can share it. + fn adopt(conn: Connection) -> Result { + block_on(Self::prepare(conn, None)) + } + fn get(&self, id: &str) -> Result { block_on(async { let mut rows = self.conn.query(SELECT_SECRET_SQL, [id]).await?; @@ -96,7 +159,7 @@ impl TursoStore { /// Copy every secret into `dst` inside a single transaction. fn copy_into(&self, dst: &TursoStore) -> Result<()> { - block_on(async { + block_on::<_, (), KeyRingError>(async { let mut rows = self.conn.query("SELECT id, value FROM secrets", ()).await?; dst.conn.execute("BEGIN", ()).await?; while let Some(row) = rows.next().await? { @@ -113,7 +176,7 @@ impl TursoStore { /// Flush the WAL into the main database file and empty the WAL. fn checkpoint(&self) -> Result<()> { - block_on(async { + block_on::<_, (), KeyRingError>(async { let mut rows = self .conn .query("PRAGMA wal_checkpoint(TRUNCATE)", ()) @@ -130,10 +193,21 @@ impl TursoStore { /// carrying their encryption configuration. pub(crate) struct TursoFile { store: TursoStore, - db_path: PathBuf, - /// Exclusive advisory lock on a sidecar file, held for the keyring's - /// lifetime so `rekey`'s rename never races another opener. - _lock: File, + storage: Storage, +} + +/// Where a keyring's database lives, and who is responsible for it. +enum Storage { + /// cryptex opened the file itself and holds the single-opener lock. + File { + db_path: PathBuf, + /// Exclusive advisory lock on a sidecar file, held for the keyring's + /// lifetime so `rekey`'s rename never races another opener. + _lock: File, + }, + /// The caller supplied the storage: a connection, or a custom IO backend + /// such as OPFS. The caller owns single-writer access. + Caller, } impl TursoFile { @@ -147,15 +221,39 @@ impl TursoFile { let store = TursoStore::open(builder(path_str(&db_path)?))?; Ok(Self { store, - db_path, - _lock: lock, + storage: Storage::File { + db_path, + _lock: lock, + }, }) } - /// Path of the main database file. + /// Open through a caller-supplied [`Builder`], e.g. one carrying a custom + /// Turso `IO`. No path is resolved and no lock file is created: the caller + /// owns the storage. + pub(crate) fn open_with(builder: Builder) -> Result { + Ok(Self { + store: TursoStore::open(builder)?, + storage: Storage::Caller, + }) + } + + /// Adopt an already-open connection. The keyring creates and owns its + /// `secrets` table and leaves every other table alone. + pub(crate) fn adopt(conn: Connection) -> Result { + Ok(Self { + store: TursoStore::adopt(conn)?, + storage: Storage::Caller, + }) + } + + /// Path of the main database file, when cryptex opened it itself. #[cfg(feature = "turso")] - pub(crate) fn db_path(&self) -> &Path { - &self.db_path + pub(crate) fn db_path(&self) -> Option<&Path> { + match &self.storage { + Storage::File { db_path, .. } => Some(db_path), + Storage::Caller => None, + } } /// Re-encrypt the keyring under the configuration produced by `builder`. @@ -163,11 +261,22 @@ impl TursoFile { /// Secrets are copied into a temporary database opened with the new /// configuration, which then atomically replaces the original. The /// original is untouched if anything fails before the rename. + /// + /// Only a keyring that cryptex opened from a path can be rekeyed; a + /// keyring adopted from a caller's connection or IO must be rekeyed by + /// the caller, who owns the storage. pub(crate) fn rekey(self, builder: B) -> Result where B: Fn(&str) -> Builder, { - let tmp_path = self.db_path.with_extension("cryptex-rekey-tmp"); + let Storage::File { db_path, _lock } = self.storage else { + return Err(KeyRingError::GeneralError { + msg: "rekey is only available for a keyring cryptex opened from a path; \ + copy the secrets into a new keyring instead" + .to_string(), + }); + }; + let tmp_path = db_path.with_extension("cryptex-rekey-tmp"); remove_db_files(&tmp_path)?; let copied = TursoStore::open(builder(path_str(&tmp_path)?)).and_then(|tmp| { @@ -180,12 +289,7 @@ impl TursoFile { } self.store.checkpoint()?; - let Self { - store, - db_path, - _lock, - } = self; - drop(store); + drop(self.store); remove_file_if_exists(&sibling_path(&tmp_path, "-wal"))?; remove_file_if_exists(&sibling_path(&db_path, "-wal"))?; fs::rename(&tmp_path, &db_path).map_err(|e| KeyRingError::GeneralError { @@ -195,8 +299,7 @@ impl TursoFile { let store = TursoStore::open(builder(path_str(&db_path)?))?; Ok(Self { store, - db_path, - _lock, + storage: Storage::File { db_path, _lock }, }) } } @@ -243,15 +346,15 @@ mod tests { #[test] fn block_on_drives_pending_future() { let mut polled = false; - let fut = std::future::poll_fn(|cx| { + let fut = std::future::poll_fn::, _>(|cx| { if polled { - std::task::Poll::Ready(7) + std::task::Poll::Ready(Ok(7)) } else { polled = true; cx.waker().wake_by_ref(); std::task::Poll::Pending } }); - assert_eq!(block_on(fut), 7); + assert_eq!(block_on(fut).unwrap(), 7); } } diff --git a/src/keyring/turso_encrypted_io.rs b/src/keyring/turso_encrypted_io.rs index 418a448..89fe412 100644 --- a/src/keyring/turso_encrypted_io.rs +++ b/src/keyring/turso_encrypted_io.rs @@ -25,7 +25,7 @@ use super::file_common::{self, derive_key_32, file_keyring, private_open_options use super::page_cipher::{self, ActiveCipher}; use super::turso_common::TursoFile; -pub use super::page_cipher::CipherAlgorithm; +pub use super::cipher::CipherAlgorithm; /// Connection parameters for [`TursoEncryptedIoKeyring`]. /// diff --git a/src/lib.rs b/src/lib.rs index 1e662a6..c880c09 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -20,6 +20,7 @@ pub use keyring::encrypted_vfs; #[cfg(any( feature = "file", feature = "encrypted-vfs", + feature = "memory", feature = "turso", feature = "turso-encrypted-io" ))] @@ -48,6 +49,9 @@ pub use keyring::linux; #[cfg(all(target_os = "macos", feature = "macos-keychain"))] #[cfg_attr(docsrs, doc(cfg(all(target_os = "macos", feature = "macos-keychain"))))] pub use keyring::macos; +#[cfg(feature = "memory")] +#[cfg_attr(docsrs, doc(cfg(feature = "memory")))] +pub use keyring::memory; #[cfg(feature = "file")] #[cfg_attr(docsrs, doc(cfg(feature = "file")))] pub use keyring::sqlcipher; From 35eb68d68756e1de53493fc831ffef0b7d09399b Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 14:34:17 -0500 Subject: [PATCH 02/18] Build for WASI, and make the CLI native-only acquire_single_opener_lock treats an Unsupported lock as success, which is what WASI reports, and the default keyring directory there is ./.cryptex instead of a home directory that does not exist. Criterion is native-only (Rayon does not build for wasm) and the CLI is split into src/native.rs so a wasm build of the binary compiles and prints that it is unsupported. cargo test --target wasm32-wasip1 --no-default-features --features turso,memory passes under wasmtime. --- .cargo/config.toml | 2 +- Cargo.toml | 7 +- README.md | 85 ++++++ src/keyring/file_common.rs | 13 + src/keyring/turso.rs | 3 + src/keyring/turso_common.rs | 2 +- src/main.rs | 517 +----------------------------------- src/native.rs | 516 +++++++++++++++++++++++++++++++++++ 8 files changed, 637 insertions(+), 508 deletions(-) create mode 100644 src/native.rs diff --git a/.cargo/config.toml b/.cargo/config.toml index b7426a0..af3bfde 100644 --- a/.cargo/config.toml +++ b/.cargo/config.toml @@ -7,4 +7,4 @@ rustflags = ["--cfg", "aes_armv8"] rustflags = ["--cfg", 'getrandom_backend="wasm_js"'] [target.wasm32-wasip1] -runner = "wasmtime" +runner = "wasmtime run --dir=." diff --git a/Cargo.toml b/Cargo.toml index fce6107..fa799e7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -86,12 +86,13 @@ whoami = "2.1.2" yubihsm = { version = "0.42", default-features = false, optional = true } zeroize = { version = "1.9.0", features = ["zeroize_derive"] } -[dev-dependencies] -criterion = { version = "0.8", features = ["html_reports"] } - [target.'cfg(not(target_family = "wasm"))'.dependencies] rpassword = "7.5.4" +# Criterion pulls in Rayon, which does not build for wasm. +[target.'cfg(not(target_family = "wasm"))'.dev-dependencies] +criterion = { version = "0.8", features = ["html_reports"] } + [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies] getrandom = { version = "0.4.3", features = ["wasm_js"], optional = true } js-sys = { version = "0.3", optional = true } diff --git a/README.md b/README.md index bee0fa2..0b71729 100644 --- a/README.md +++ b/README.md @@ -100,6 +100,91 @@ CRYPTEX_ARGON2_MEMORY=32768 CRYPTEX_ARGON2_THREADS=3 CRYPTEX_ARGON2_PARALLEL=2 c The program can be compiled from any OS to run on any OS. Cryptex-CLI is the command line tool while Cryptex is the library. +### In-memory keyrings + +The `memory` feature adds `MemoryKeyring`, which keeps its secrets in RAM and +never writes a file. It builds for every target, including wasm. Secrets leave +memory only as a single AEAD-sealed blob: + +```rust +use cryptex::KeyRing; +use cryptex::memory::{ConnectionParams, MemoryKeyring}; + +let params: ConnectionParams = + "password= salt=".parse().unwrap(); +let mut keyring = MemoryKeyring::with_params(¶ms)?; +keyring.set_secret("token", b"secret value")?; + +// Persist this anywhere you like; it is sealed with a fresh nonce. +let blob = keyring.export()?; +// The salt, cipher and Argon2 parameters travel inside the blob. +let mut reopened = MemoryKeyring::import(&blob, b"")?; +# Ok::<(), cryptex::KeyRingError>(()) +``` + +A blob made from `key=` instead of a password needs that same raw key to +open. `rekey` re-derives the key without touching the secrets. + +--- + +## WebAssembly and WASI + +`cryptex` builds for `wasm32-unknown-unknown` and for `wasm32-wasip1` / +`wasm32-wasip2`. Which backends exist there: + +| Feature | `wasm32-unknown-unknown` | WASI | Notes | +|---------|--------------------------|------|-------| +| `memory` | yes | yes | encrypted in RAM, export/import | +| `turso` | yes | yes | Turso's native page encryption | +| `turso-encrypted-io` | yes | yes | page cipher in a custom IO | +| `file`, `encrypted-vfs` | no | no | SQLCipher and the bundled C VFS are native only | +| OS keyrings, `yubihsm-*` | no | no | no OS keychain or USB device | + +Asking for an unsupported backend on wasm is a compile error that names the +problem, rather than a linker failure. + +`getrandom` needs its Web Crypto backend on `wasm32-unknown-unknown`. The +repository's `.cargo/config.toml` sets it, and a CI job that overrides +`RUSTFLAGS` must repeat it: + +```bash +RUSTFLAGS='--cfg getrandom_backend="wasm_js"' \ + cargo check --target wasm32-unknown-unknown --no-default-features --features turso +``` + +### Bringing your own storage + +`TursoKeyring` can adopt a connection you opened, or open through an IO you +supply, so one database can hold the keyring's `secrets` table and your own +tables under a single key: + +```rust +use cryptex::turso::TursoKeyring; + +// A connection opened by the caller, e.g. with a custom IO and encryption. +let keyring = TursoKeyring::from_connection(conn)?; + +// Or let cryptex build the database through your IO (such as OPFS). +let keyring = TursoKeyring::with_io(io, "keyring.db3", ¶ms)?; +# Ok::<(), cryptex::KeyRingError>(()) +``` + +In both cases cryptex creates and owns only its own tables, and `rekey` reports +an error because cryptex does not own that storage: copy the secrets into a +keyring that owns its file instead. `cryptex::turso` re-exports `Connection`, +`TursoBuilder` and `core` so callers construct matching types. + +Turso's synchronous API is driven on the current thread. Native builds park the +thread while a future is pending; wasm builds poll a bounded number of times +and return an error instead of spinning, so an IO backend must complete its +reads in place. + +On WASI there is no file locking: `try_lock` reports `Unsupported`, which the +keyring treats as success, and the default keyring directory is `./.cryptex` +because there is no home directory. Keep a single writer per database there. + +The CLI is native only: a wasm binary prints that and exits. + --- ## KMS/HSM Backends diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 1787f2e..46b8d24 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -402,6 +402,11 @@ pub(crate) fn derive_key_32( pub(crate) fn get_keyring_file(in_path: Option, file_name: &str) -> Result { let mut path = match in_path { None => { + // WASI has no home directory, and `CARGO_MANIFEST_DIR` is the + // build machine's path, so keep the keyring next to the program. + #[cfg(target_os = "wasi")] + let mut path = std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")); + #[cfg(not(target_os = "wasi"))] let mut path = dirs::home_dir().unwrap_or_else(|| { dirs::document_dir().unwrap_or_else(|| { dirs::data_local_dir() @@ -493,6 +498,9 @@ pub(crate) fn acquire_single_opener_lock(db_path: &Path) -> Result { Err(TryLockError::WouldBlock) => Err(KeyRingError::AccessDenied { msg: "keyring is already open by another process".to_string(), }), + // WASI and some network filesystems do not implement locking; a + // keyring there relies on the caller keeping a single writer. + Err(TryLockError::Error(e)) if e.kind() == std::io::ErrorKind::Unsupported => Ok(file), Err(TryLockError::Error(e)) => Err(KeyRingError::GeneralError { msg: format!("unable to lock keyring: {}", e), }), @@ -773,6 +781,11 @@ pub(crate) mod test_support { impl TestDir { pub(crate) fn new(name: &str) -> Self { + // Under WASI only the preopened directory is reachable, so use a + // path relative to it. + #[cfg(target_os = "wasi")] + let path = PathBuf::from(name); + #[cfg(not(target_os = "wasi"))] let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join(name); let _ = std::fs::remove_dir_all(&path); Self(path) diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index a53e3e5..29acf55 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -237,6 +237,9 @@ mod tests { { let mut kr = TursoKeyring::with_params(&correct, dir.keyring_dir()).unwrap(); kr.set_secret("x", b"secret").unwrap(); + // WASI has no file locking, so a second opener is not refused + // there; callers keep a single writer instead. + #[cfg(not(target_os = "wasi"))] assert!(matches!( TursoKeyring::with_params(&correct, dir.keyring_dir()), Err(KeyRingError::AccessDenied { .. }) diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index fa8ac47..3b8185f 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -77,7 +77,7 @@ impl Wake for SpinWaker { } #[cfg(target_family = "wasm")] -fn block_on(fut: F) -> Result +pub(crate) fn block_on(fut: F) -> Result where F: Future>, E: Into, diff --git a/src/main.rs b/src/main.rs index 9a38c1d..6ab6d95 100644 --- a/src/main.rs +++ b/src/main.rs @@ -11,514 +11,25 @@ trivial_numeric_casts )] -use clap::{Arg, ArgMatches, Command}; -use colored::Colorize; +//! The `cryptex` command-line tool. +//! +//! The CLI talks to OS keyrings, files and YubiHSM devices, none of which +//! exist in a browser or WASI sandbox, so a wasm build reports that instead of +//! exposing commands that cannot work. Use the library, or the JS bindings on +//! wasm. -// ── Imports used only when at least one active backend is compiled in ───────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::fs::File; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::io::{self, IsTerminal, Read, Write}; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::path::PathBuf; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use zeroize::Zeroize; - -// ── Shared backend imports ──────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use cryptex::{KeyRing, KeyRingSecret}; - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -use std::collections::BTreeMap; - -// ── OS keyring ──────────────────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -use cryptex::{ListKeyRing, PeekableKeyRing, get_os_keyring}; - -#[cfg(all(target_os = "macos", feature = "macos-keychain"))] -use cryptex::macos::MacOsKeyRing as OsKeyRing; - -#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] -use cryptex::linux::LinuxOsKeyRing as OsKeyRing; - -#[cfg(all(target_os = "windows", feature = "windows-credentials"))] -use cryptex::windows::WindowsOsKeyRing as OsKeyRing; - -// ── YubiHSM ─────────────────────────────────────────────────────────────────── - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -use cryptex::NewKeyRing; - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -use cryptex::yubihsm::YubiHsmKeyRing; - -// ───────────────────────────────────────────────────────────────────────────── +#[cfg(not(target_family = "wasm"))] +mod native; +#[cfg(not(target_family = "wasm"))] fn main() { - let matches = Command::new("cryptex") - .version(env!("CARGO_PKG_VERSION")) - .author("Michael Lodder") - .about("Platform-independent CLI for storing and retrieving secrets from secure keyrings") - .arg( - Arg::new("keyring") - .long("keyring") - .short('k') - .value_name("TYPE") - .global(true) - .help("Keyring backend to use: 'os' (default) or 'yubihsm'"), - ) - .subcommand( - Command::new("get") - .about("Retrieve a secret by ID") - .arg( - Arg::new("SERVICE") - .help("Service name (OS) or connection string (yubihsm)") - .required(true) - .index(1), - ) - .arg( - Arg::new("ID") - .help("The secret ID. If omitted, read from STDIN") - .required(false) - .index(2), - ), - ) - .subcommand( - Command::new("set") - .about("Save a secret by ID") - .arg( - Arg::new("SERVICE") - .help("Service name (OS) or connection string (yubihsm)") - .required(true) - .index(1), - ) - .arg( - Arg::new("ID") - .help("The secret ID") - .required(true) - .index(2), - ) - .arg( - Arg::new("SECRET") - .help("The secret value. If omitted, read from STDIN") - .required(false) - .index(3), - ), - ) - .subcommand( - Command::new("delete") - .about("Delete a secret by ID") - .arg( - Arg::new("SERVICE") - .help("Service name (OS) or connection string (yubihsm)") - .required(true) - .index(1), - ) - .arg( - Arg::new("ID") - .help("The secret ID. If omitted, read from STDIN") - .required(false) - .index(2), - ), - ) - .subcommand( - Command::new("peek") - .about("Inspect OS keyring entries without full retrieval (OS backends only)") - .arg( - Arg::new("ID") - .help("Filter as comma-separated name=value pairs (e.g. service=aws,account=key)") - .required(false) - .index(1), - ), - ) - .subcommand( - Command::new("list") - .about("List secret IDs. For 'os': lists all. For 'yubihsm': requires a connection string.") - .arg( - Arg::new("SERVICE") - .help("Connection string (required for 'yubihsm')") - .required(false) - .index(1), - ), - ) - .get_matches(); - - dispatch(&matches); -} - -fn dispatch(matches: &ArgMatches) { - let keyring_type = matches - .get_one::("keyring") - .map(|s| s.as_str()) - .unwrap_or("os"); - - match keyring_type { - "yubihsm" => { - #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] - dispatch_yubihsm(matches); - #[cfg(not(any(feature = "yubihsm-usb", feature = "yubihsm-http")))] - die::<()>( - "YubiHSM support is not compiled in. \ - Enable the 'yubihsm-usb' or 'yubihsm-http' feature.", - ); - } - "os" => dispatch_os(matches), - other => die::<()>(&format!( - "Unknown keyring type '{}'. Valid options: os, yubihsm", - other - )), - } + native::main(); } -// ── OS keyring dispatch ─────────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn dispatch_os(matches: &ArgMatches) { - if let Some(m) = matches.subcommand_matches("get") { - os_get(m); - } else if let Some(m) = matches.subcommand_matches("set") { - os_set(m); - } else if let Some(m) = matches.subcommand_matches("delete") { - os_delete(m); - } else if let Some(m) = matches.subcommand_matches("peek") { - os_peek(m); - } else if matches.subcommand_matches("list").is_some() { - os_list(); - } else { - die::<()>("Please specify a command: get | set | delete | peek | list"); - } -} - -#[cfg(not(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -)))] -fn dispatch_os(_matches: &ArgMatches) { - die::<()>( - "No OS keyring available for this platform/feature combination. \ - Use '--keyring yubihsm' or enable a platform keyring feature.", +#[cfg(target_family = "wasm")] +fn main() { + eprintln!( + "cryptex CLI is not supported on wasm; use the cryptex library or its JS bindings instead" ); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_get(matches: &ArgMatches) { - let mut keyring = os_open(matches); - let id = get_id(matches, true); - let secret = keyring - .get_secret(&id) - .unwrap_or_else(|e| die::(&e.to_string())); - io::stdout().write_all(secret.as_slice()).unwrap(); - io::stdout().flush().unwrap(); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_set(matches: &ArgMatches) { - let mut keyring = os_open(matches); - let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); - let mut secret = read_input(matches, "SECRET", true); - keyring - .set_secret(id, &secret) - .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); - secret.zeroize(); - println!("{}", "Success".green()); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_delete(matches: &ArgMatches) { - let mut keyring = os_open(matches); - let id = get_id(matches, true); - keyring - .delete_secret(&id) - .unwrap_or_else(|e| die::<()>(&e.to_string())); - println!("{}", "Success".green()); -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_peek(matches: &ArgMatches) { - let id = get_id(matches, false); - let secrets = OsKeyRing::peek_secret(&id) - .unwrap_or_else(|e| die::>(&e.to_string())); - if secrets.len() == 1 && !id.is_empty() { - io::stdout().write_all(secrets[0].1.as_slice()).unwrap(); - io::stdout().flush().unwrap(); - println!(); - } else { - for s in secrets { - print!("{} -> ", s.0); - io::stdout().write_all(s.1.as_slice()).unwrap(); - println!(); - io::stdout().flush().unwrap(); - } - } -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), -))] -fn os_list() { - let secret_names = OsKeyRing::list_secrets() - .unwrap_or_else(|e| die::>>(&e.to_string())); - for s in secret_names { - println!("{:?}", s); - } -} - -#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] -fn os_open(matches: &ArgMatches) -> OsKeyRing<'_> { - let service = matches - .get_one::("SERVICE") - .map(|s| s.as_str()) - .unwrap(); - get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), -))] -fn os_open(matches: &ArgMatches) -> OsKeyRing { - let service = matches - .get_one::("SERVICE") - .map(|s| s.as_str()) - .unwrap(); - get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) -} - -// ── YubiHSM dispatch ───────────────────────────────────────────────────────── - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn dispatch_yubihsm(matches: &ArgMatches) { - if let Some(m) = matches.subcommand_matches("get") { - yubihsm_get(m); - } else if let Some(m) = matches.subcommand_matches("set") { - yubihsm_set(m); - } else if let Some(m) = matches.subcommand_matches("delete") { - yubihsm_delete(m); - } else if let Some(m) = matches.subcommand_matches("list") { - yubihsm_list(m); - } else if matches.subcommand_matches("peek").is_some() { - die::<()>("The 'peek' command is not supported for the YubiHSM backend."); - } else { - die::<()>("Please specify a command: get | set | delete | list"); - } -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_open(matches: &ArgMatches) -> YubiHsmKeyRing { - let connstr = matches - .get_one::("SERVICE") - .map(|s| s.as_str()) - .unwrap_or_else(|| die("A YubiHSM connection string is required as the SERVICE argument")); - YubiHsmKeyRing::new(connstr) - .unwrap_or_else(|e| die(&format!("Failed to connect to YubiHSM: {}", e))) -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_get(matches: &ArgMatches) { - let mut ring = yubihsm_open(matches); - let id = get_id(matches, true); - let secret = ring - .get_secret(&id) - .unwrap_or_else(|e| die::(&e.to_string())); - io::stdout().write_all(secret.as_slice()).unwrap(); - io::stdout().flush().unwrap(); -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_set(matches: &ArgMatches) { - let mut ring = yubihsm_open(matches); - let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); - let mut secret = read_input(matches, "SECRET", true); - ring.set_secret(id, &secret) - .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); - secret.zeroize(); - println!("{}", "Success".green()); -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_delete(matches: &ArgMatches) { - let mut ring = yubihsm_open(matches); - let id = get_id(matches, true); - ring.delete_secret(&id) - .unwrap_or_else(|e| die::<()>(&e.to_string())); - println!("{}", "Success".green()); -} - -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -fn yubihsm_list(matches: &ArgMatches) { - let ring = yubihsm_open(matches); - let entries = ring - .list_hsm_secrets() - .unwrap_or_else(|e| die::>>(&e.to_string())); - for entry in entries { - println!("{:?}", entry); - } -} - -// ── Shared helpers ──────────────────────────────────────────────────────────── - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn get_id(matches: &ArgMatches, read_stdin: bool) -> String { - let bytes = read_input(matches, "ID", read_stdin); - String::from_utf8(bytes).unwrap_or_else(|_| die("ID is not valid UTF-8")) -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn read_input(matches: &ArgMatches, name: &str, read_stdin: bool) -> Vec { - match matches.get_one::(name).map(|s| s.as_str()) { - Some(text) => match get_file(text) { - Some(file) => match File::open(file.as_path()) { - Ok(mut f) => read_stream(&mut f), - Err(_) => die(&format!("Unable to read file {}", file.to_str().unwrap())), - }, - None => text.as_bytes().to_vec(), - }, - None => { - if io::stdin().is_terminal() { - if read_stdin { - rpassword::prompt_password("Enter Secret: ") - .unwrap() - .as_bytes() - .to_vec() - } else { - Vec::new() - } - } else { - let mut f = io::stdin(); - read_stream(&mut f) - } - } - } -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn read_stream(f: &mut R) -> Vec { - let mut bytes = Vec::new(); - let mut buffer = [0u8; 4096]; - loop { - match f.read(&mut buffer) { - Ok(0) => break, - Ok(n) => bytes.extend_from_slice(&buffer[..n]), - Err(_) => break, - } - } - bytes -} - -#[cfg(any( - all(target_os = "macos", feature = "macos-keychain"), - all(target_os = "windows", feature = "windows-credentials"), - all(target_os = "linux", feature = "linux-secret-service"), - feature = "yubihsm-usb", - feature = "yubihsm-http", -))] -fn get_file(name: &str) -> Option { - let mut file = PathBuf::from(name); - if file.as_path().is_file() { - let metadata = file - .as_path() - .symlink_metadata() - .expect("symlink_metadata call failed"); - if metadata.file_type().is_symlink() { - match file.as_path().read_link() { - Ok(f) => file = f, - Err(_) => die::<()>(&format!("Can't read the symbolic link: {}", name)), - } - } - Some(file) - } else { - None - } -} - -fn die(final_message: &str) -> R { - eprintln!("{}", final_message.red()); std::process::exit(1); } diff --git a/src/native.rs b/src/native.rs new file mode 100644 index 0000000..d776f1c --- /dev/null +++ b/src/native.rs @@ -0,0 +1,516 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ + +use clap::{Arg, ArgMatches, Command}; +use colored::Colorize; + +// ── Imports used only when at least one active backend is compiled in ───────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::fs::File; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::io::{self, IsTerminal, Read, Write}; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::path::PathBuf; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use zeroize::Zeroize; + +// ── Shared backend imports ──────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use cryptex::{KeyRing, KeyRingSecret}; + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +use std::collections::BTreeMap; + +// ── OS keyring ──────────────────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +use cryptex::{ListKeyRing, PeekableKeyRing, get_os_keyring}; + +#[cfg(all(target_os = "macos", feature = "macos-keychain"))] +use cryptex::macos::MacOsKeyRing as OsKeyRing; + +#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] +use cryptex::linux::LinuxOsKeyRing as OsKeyRing; + +#[cfg(all(target_os = "windows", feature = "windows-credentials"))] +use cryptex::windows::WindowsOsKeyRing as OsKeyRing; + +// ── YubiHSM ─────────────────────────────────────────────────────────────────── + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +use cryptex::NewKeyRing; + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +use cryptex::yubihsm::YubiHsmKeyRing; + +// ───────────────────────────────────────────────────────────────────────────── + +pub(crate) fn main() { + let matches = Command::new("cryptex") + .version(env!("CARGO_PKG_VERSION")) + .author("Michael Lodder") + .about("Platform-independent CLI for storing and retrieving secrets from secure keyrings") + .arg( + Arg::new("keyring") + .long("keyring") + .short('k') + .value_name("TYPE") + .global(true) + .help("Keyring backend to use: 'os' (default) or 'yubihsm'"), + ) + .subcommand( + Command::new("get") + .about("Retrieve a secret by ID") + .arg( + Arg::new("SERVICE") + .help("Service name (OS) or connection string (yubihsm)") + .required(true) + .index(1), + ) + .arg( + Arg::new("ID") + .help("The secret ID. If omitted, read from STDIN") + .required(false) + .index(2), + ), + ) + .subcommand( + Command::new("set") + .about("Save a secret by ID") + .arg( + Arg::new("SERVICE") + .help("Service name (OS) or connection string (yubihsm)") + .required(true) + .index(1), + ) + .arg( + Arg::new("ID") + .help("The secret ID") + .required(true) + .index(2), + ) + .arg( + Arg::new("SECRET") + .help("The secret value. If omitted, read from STDIN") + .required(false) + .index(3), + ), + ) + .subcommand( + Command::new("delete") + .about("Delete a secret by ID") + .arg( + Arg::new("SERVICE") + .help("Service name (OS) or connection string (yubihsm)") + .required(true) + .index(1), + ) + .arg( + Arg::new("ID") + .help("The secret ID. If omitted, read from STDIN") + .required(false) + .index(2), + ), + ) + .subcommand( + Command::new("peek") + .about("Inspect OS keyring entries without full retrieval (OS backends only)") + .arg( + Arg::new("ID") + .help("Filter as comma-separated name=value pairs (e.g. service=aws,account=key)") + .required(false) + .index(1), + ), + ) + .subcommand( + Command::new("list") + .about("List secret IDs. For 'os': lists all. For 'yubihsm': requires a connection string.") + .arg( + Arg::new("SERVICE") + .help("Connection string (required for 'yubihsm')") + .required(false) + .index(1), + ), + ) + .get_matches(); + + dispatch(&matches); +} + +fn dispatch(matches: &ArgMatches) { + let keyring_type = matches + .get_one::("keyring") + .map(|s| s.as_str()) + .unwrap_or("os"); + + match keyring_type { + "yubihsm" => { + #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] + dispatch_yubihsm(matches); + #[cfg(not(any(feature = "yubihsm-usb", feature = "yubihsm-http")))] + die::<()>( + "YubiHSM support is not compiled in. \ + Enable the 'yubihsm-usb' or 'yubihsm-http' feature.", + ); + } + "os" => dispatch_os(matches), + other => die::<()>(&format!( + "Unknown keyring type '{}'. Valid options: os, yubihsm", + other + )), + } +} + +// ── OS keyring dispatch ─────────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn dispatch_os(matches: &ArgMatches) { + if let Some(m) = matches.subcommand_matches("get") { + os_get(m); + } else if let Some(m) = matches.subcommand_matches("set") { + os_set(m); + } else if let Some(m) = matches.subcommand_matches("delete") { + os_delete(m); + } else if let Some(m) = matches.subcommand_matches("peek") { + os_peek(m); + } else if matches.subcommand_matches("list").is_some() { + os_list(); + } else { + die::<()>("Please specify a command: get | set | delete | peek | list"); + } +} + +#[cfg(not(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +)))] +fn dispatch_os(_matches: &ArgMatches) { + die::<()>( + "No OS keyring available for this platform/feature combination. \ + Use '--keyring yubihsm' or enable a platform keyring feature.", + ); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_get(matches: &ArgMatches) { + let mut keyring = os_open(matches); + let id = get_id(matches, true); + let secret = keyring + .get_secret(&id) + .unwrap_or_else(|e| die::(&e.to_string())); + io::stdout().write_all(secret.as_slice()).unwrap(); + io::stdout().flush().unwrap(); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_set(matches: &ArgMatches) { + let mut keyring = os_open(matches); + let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); + let mut secret = read_input(matches, "SECRET", true); + keyring + .set_secret(id, &secret) + .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); + secret.zeroize(); + println!("{}", "Success".green()); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_delete(matches: &ArgMatches) { + let mut keyring = os_open(matches); + let id = get_id(matches, true); + keyring + .delete_secret(&id) + .unwrap_or_else(|e| die::<()>(&e.to_string())); + println!("{}", "Success".green()); +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_peek(matches: &ArgMatches) { + let id = get_id(matches, false); + let secrets = OsKeyRing::peek_secret(&id) + .unwrap_or_else(|e| die::>(&e.to_string())); + if secrets.len() == 1 && !id.is_empty() { + io::stdout().write_all(secrets[0].1.as_slice()).unwrap(); + io::stdout().flush().unwrap(); + println!(); + } else { + for s in secrets { + print!("{} -> ", s.0); + io::stdout().write_all(s.1.as_slice()).unwrap(); + println!(); + io::stdout().flush().unwrap(); + } + } +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), +))] +fn os_list() { + let secret_names = OsKeyRing::list_secrets() + .unwrap_or_else(|e| die::>>(&e.to_string())); + for s in secret_names { + println!("{:?}", s); + } +} + +#[cfg(all(target_os = "linux", feature = "linux-secret-service"))] +fn os_open(matches: &ArgMatches) -> OsKeyRing<'_> { + let service = matches + .get_one::("SERVICE") + .map(|s| s.as_str()) + .unwrap(); + get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), +))] +fn os_open(matches: &ArgMatches) -> OsKeyRing { + let service = matches + .get_one::("SERVICE") + .map(|s| s.as_str()) + .unwrap(); + get_os_keyring(service).unwrap_or_else(|e| die(&format!("Unable to open OS keyring: {}", e))) +} + +// ── YubiHSM dispatch ───────────────────────────────────────────────────────── + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn dispatch_yubihsm(matches: &ArgMatches) { + if let Some(m) = matches.subcommand_matches("get") { + yubihsm_get(m); + } else if let Some(m) = matches.subcommand_matches("set") { + yubihsm_set(m); + } else if let Some(m) = matches.subcommand_matches("delete") { + yubihsm_delete(m); + } else if let Some(m) = matches.subcommand_matches("list") { + yubihsm_list(m); + } else if matches.subcommand_matches("peek").is_some() { + die::<()>("The 'peek' command is not supported for the YubiHSM backend."); + } else { + die::<()>("Please specify a command: get | set | delete | list"); + } +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_open(matches: &ArgMatches) -> YubiHsmKeyRing { + let connstr = matches + .get_one::("SERVICE") + .map(|s| s.as_str()) + .unwrap_or_else(|| die("A YubiHSM connection string is required as the SERVICE argument")); + YubiHsmKeyRing::new(connstr) + .unwrap_or_else(|e| die(&format!("Failed to connect to YubiHSM: {}", e))) +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_get(matches: &ArgMatches) { + let mut ring = yubihsm_open(matches); + let id = get_id(matches, true); + let secret = ring + .get_secret(&id) + .unwrap_or_else(|e| die::(&e.to_string())); + io::stdout().write_all(secret.as_slice()).unwrap(); + io::stdout().flush().unwrap(); +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_set(matches: &ArgMatches) { + let mut ring = yubihsm_open(matches); + let id = matches.get_one::("ID").map(|s| s.as_str()).unwrap(); + let mut secret = read_input(matches, "SECRET", true); + ring.set_secret(id, &secret) + .unwrap_or_else(|e| die::<()>(&format!("Failed: {}", e))); + secret.zeroize(); + println!("{}", "Success".green()); +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_delete(matches: &ArgMatches) { + let mut ring = yubihsm_open(matches); + let id = get_id(matches, true); + ring.delete_secret(&id) + .unwrap_or_else(|e| die::<()>(&e.to_string())); + println!("{}", "Success".green()); +} + +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +fn yubihsm_list(matches: &ArgMatches) { + let ring = yubihsm_open(matches); + let entries = ring + .list_hsm_secrets() + .unwrap_or_else(|e| die::>>(&e.to_string())); + for entry in entries { + println!("{:?}", entry); + } +} + +// ── Shared helpers ──────────────────────────────────────────────────────────── + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn get_id(matches: &ArgMatches, read_stdin: bool) -> String { + let bytes = read_input(matches, "ID", read_stdin); + String::from_utf8(bytes).unwrap_or_else(|_| die("ID is not valid UTF-8")) +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn read_input(matches: &ArgMatches, name: &str, read_stdin: bool) -> Vec { + match matches.get_one::(name).map(|s| s.as_str()) { + Some(text) => match get_file(text) { + Some(file) => match File::open(file.as_path()) { + Ok(mut f) => read_stream(&mut f), + Err(_) => die(&format!("Unable to read file {}", file.to_str().unwrap())), + }, + None => text.as_bytes().to_vec(), + }, + None => { + if io::stdin().is_terminal() { + if read_stdin { + rpassword::prompt_password("Enter Secret: ") + .unwrap() + .as_bytes() + .to_vec() + } else { + Vec::new() + } + } else { + let mut f = io::stdin(); + read_stream(&mut f) + } + } + } +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn read_stream(f: &mut R) -> Vec { + let mut bytes = Vec::new(); + let mut buffer = [0u8; 4096]; + loop { + match f.read(&mut buffer) { + Ok(0) => break, + Ok(n) => bytes.extend_from_slice(&buffer[..n]), + Err(_) => break, + } + } + bytes +} + +#[cfg(any( + all(target_os = "macos", feature = "macos-keychain"), + all(target_os = "windows", feature = "windows-credentials"), + all(target_os = "linux", feature = "linux-secret-service"), + feature = "yubihsm-usb", + feature = "yubihsm-http", +))] +fn get_file(name: &str) -> Option { + let mut file = PathBuf::from(name); + if file.as_path().is_file() { + let metadata = file + .as_path() + .symlink_metadata() + .expect("symlink_metadata call failed"); + if metadata.file_type().is_symlink() { + match file.as_path().read_link() { + Ok(f) => file = f, + Err(_) => die::<()>(&format!("Can't read the symbolic link: {}", name)), + } + } + Some(file) + } else { + None + } +} + +fn die(final_message: &str) -> R { + eprintln!("{}", final_message.red()); + std::process::exit(1); +} From ff21f53fbf0822cd427e477e88ed97e187da8678 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 14:48:12 -0500 Subject: [PATCH 03/18] Keep a Turso keyring in memory and export it as one image Turso's file traffic now goes through a PageStore trait, so the page cipher works over a native file, an in-memory buffer or (next) an OPFS handle. On top of it, a Turso IO keeps every database and WAL file in memory, reads and writes complete in place, and the clock comes from the JavaScript runtime: the default clock calls Instant::now, which panics on wasm. That gives TursoKeyring::in_memory, from_bytes and export, which is how a browser persists a keyring without a filesystem. --- Cargo.toml | 2 +- src/keyring.rs | 9 + src/keyring/page_cipher.rs | 56 +++--- src/keyring/page_store.rs | 125 ++++++++++++ src/keyring/turso.rs | 81 +++++++- src/keyring/turso_common.rs | 2 + src/keyring/turso_encrypted_io.rs | 9 +- src/keyring/turso_web.rs | 316 ++++++++++++++++++++++++++++++ 8 files changed, 568 insertions(+), 32 deletions(-) create mode 100644 src/keyring/page_store.rs create mode 100644 src/keyring/turso_web.rs diff --git a/Cargo.toml b/Cargo.toml index fa799e7..30ca8a3 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -56,7 +56,7 @@ js = [ "dep:js-sys", ] encrypted-vfs = ["dep:argon2", "dep:dirs", "dep:rusqlite", "rusqlite/bundled", "dep:chacha20poly1305", "dep:aes-gcm", "dep:sqlite-plugin", "dep:getrandom"] -turso = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen"] +turso = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen", "dep:js-sys", "dep:wasm-bindgen"] turso-encrypted-io = ["dep:argon2", "dep:dirs", "dep:turso", "dep:bindgen", "dep:chacha20poly1305", "dep:aes-gcm", "dep:getrandom"] linux-secret-service = ["secret-service", "uzers"] macos-keychain = ["security-framework", "security-framework-sys", "core-foundation", "core-foundation-sys", "uzers"] diff --git a/src/keyring.rs b/src/keyring.rs index c68ddc1..9d173b5 100644 --- a/src/keyring.rs +++ b/src/keyring.rs @@ -32,6 +32,13 @@ pub mod macos; pub mod memory; #[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))] mod page_cipher; +#[cfg(any( + feature = "encrypted-vfs", + feature = "turso", + feature = "turso-encrypted-io", + feature = "opfs" +))] +mod page_store; #[cfg(feature = "file")] pub mod sqlcipher; #[cfg(any(feature = "file", feature = "encrypted-vfs"))] @@ -42,6 +49,8 @@ pub mod turso; mod turso_common; #[cfg(feature = "turso-encrypted-io")] pub mod turso_encrypted_io; +#[cfg(feature = "turso")] +mod turso_web; #[cfg(all(target_os = "windows", feature = "windows-credentials"))] pub mod windows; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] diff --git a/src/keyring/page_cipher.rs b/src/keyring/page_cipher.rs index 70d1b96..97a3b83 100644 --- a/src/keyring/page_cipher.rs +++ b/src/keyring/page_cipher.rs @@ -2,21 +2,23 @@ Copyright Michael Lodder. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ -//! Page-level AEAD encryption shared by the SQLite encrypted VFS and the -//! Turso encrypted IO backend. +//! Page-level AEAD encryption shared by the SQLite encrypted VFS, the Turso +//! encrypted IO backend and the browser page stores. //! -//! Every 4096-byte logical page is stored on disk as +//! Every 4096-byte logical page is stored as //! `[ciphertext(4096) | nonce(12) | tag(16)]`, with the page number bound as -//! associated data so pages cannot be swapped. +//! associated data so pages cannot be swapped. The byte layout is identical +//! for every [`PageStore`], so a file written natively opens unchanged from +//! OPFS and the other way round. use super::cipher::CipherAlgorithm; +use super::page_store::PageStore; use aes_gcm::Aes256Gcm; use chacha20poly1305::{ ChaCha20Poly1305, aead::{Aead, KeyInit, Payload}, }; -use std::fs::File; -use std::io::{self, Read, Seek, SeekFrom, Write}; +use std::io; use std::iter; pub(crate) const LOGICAL_PAGE_SIZE: usize = 4096; @@ -104,27 +106,30 @@ impl ActiveCipher { /// Read and decrypt physical page `page_no`, or return zeros if it lies /// past the end of the file. - fn load_page(&self, file: &mut File, page_no: usize) -> io::Result<[u8; LOGICAL_PAGE_SIZE]> { + fn load_page( + &self, + store: &mut S, + page_no: usize, + ) -> io::Result<[u8; LOGICAL_PAGE_SIZE]> { let physical_offset = (page_no * PHYSICAL_PAGE_SIZE) as u64; - if physical_offset >= file.metadata()?.len() { + if physical_offset >= store.len()? { return Ok([0u8; LOGICAL_PAGE_SIZE]); } let mut block = [0u8; PHYSICAL_PAGE_SIZE]; - file.seek(SeekFrom::Start(physical_offset))?; - file.read_exact(&mut block)?; + store.read_exact_at(physical_offset, &mut block)?; self.decrypt_page(page_no as u64, &block) } /// Read `data.len()` logical bytes starting at logical `offset`. /// Bytes past the end of the file read as zeros. - pub(crate) fn read_at( + pub(crate) fn read_at( &self, - file: &mut File, + store: &mut S, offset: usize, data: &mut [u8], ) -> io::Result { for chunk in page_chunks(offset, data.len()) { - let page = self.load_page(file, chunk.page_no)?; + let page = self.load_page(store, chunk.page_no)?; data[chunk.buf_pos..chunk.buf_pos + chunk.len] .copy_from_slice(&page[chunk.intra..chunk.intra + chunk.len]); } @@ -132,9 +137,9 @@ impl ActiveCipher { } /// Write `data` at logical `offset`, re-encrypting every touched page. - pub(crate) fn write_at( + pub(crate) fn write_at( &self, - file: &mut File, + store: &mut S, offset: usize, data: &[u8], ) -> io::Result { @@ -142,29 +147,29 @@ impl ActiveCipher { let mut page = if chunk.len == LOGICAL_PAGE_SIZE { [0u8; LOGICAL_PAGE_SIZE] } else { - self.load_page(file, chunk.page_no)? + self.load_page(store, chunk.page_no)? }; page[chunk.intra..chunk.intra + chunk.len] .copy_from_slice(&data[chunk.buf_pos..chunk.buf_pos + chunk.len]); let block = self.encrypt_page(chunk.page_no as u64, &page)?; - file.seek(SeekFrom::Start((chunk.page_no * PHYSICAL_PAGE_SIZE) as u64))?; - file.write_all(&block)?; + let physical_offset = (chunk.page_no * PHYSICAL_PAGE_SIZE) as u64; + store.write_all_at(physical_offset, &block)?; } Ok(data.len()) } } -/// Logical size of an encrypted file: whole physical pages × logical page size. -pub(crate) fn logical_size(file: &File) -> io::Result { - let phys = file.metadata()?.len(); +/// Logical size of an encrypted store: whole physical pages × logical page size. +pub(crate) fn logical_size(store: &S) -> io::Result { + let phys = store.len()?; Ok((phys / PHYSICAL_PAGE_SIZE as u64) * LOGICAL_PAGE_SIZE as u64) } -/// Truncate an encrypted file to hold `logical_size` bytes (rounded up to a page). -pub(crate) fn truncate(file: &File, logical_size: usize) -> io::Result<()> { +/// Truncate an encrypted store to hold `logical_size` bytes (rounded up to a page). +pub(crate) fn truncate(store: &mut S, logical_size: usize) -> io::Result<()> { let num_pages = logical_size.div_ceil(LOGICAL_PAGE_SIZE); - file.set_len((num_pages * PHYSICAL_PAGE_SIZE) as u64) + store.set_len((num_pages * PHYSICAL_PAGE_SIZE) as u64) } /// The part of one logical page touched by a byte-range access. @@ -202,6 +207,7 @@ fn page_chunks(offset: usize, len: usize) -> impl Iterator { mod tests { use super::*; use std::fs; + use std::fs::File; use std::path::PathBuf; fn temp_file(name: &str) -> (PathBuf, File) { @@ -257,7 +263,7 @@ mod tests { let wrong = ActiveCipher::from_key(alg, &[8u8; 32]); assert!(wrong.read_at(&mut f, 0, &mut out).is_err()); - truncate(&f, 1).unwrap(); + truncate(&mut f, 1).unwrap(); assert_eq!(logical_size(&f).unwrap(), LOGICAL_PAGE_SIZE as u64); drop(f); diff --git a/src/keyring/page_store.rs b/src/keyring/page_store.rs new file mode 100644 index 0000000..dc13ce9 --- /dev/null +++ b/src/keyring/page_store.rs @@ -0,0 +1,125 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Byte-addressable storage behind an encrypted page file. +//! +//! The cipher in [`page_cipher`](super::page_cipher) works on pages; this +//! module supplies the bytes. Native keyrings use a file, browser keyrings a +//! buffer or an OPFS handle. + +#![allow(dead_code)] + +use std::fs::File; +use std::io::{self, Read, Seek, SeekFrom, Write}; + +/// Byte-addressable storage behind an encrypted page file. +/// +/// Implementations are a native file, an in-memory buffer and a browser OPFS +/// sync access handle. `len` and `set_len` work in physical bytes; the cipher +/// translates to logical pages. +pub(crate) trait PageStore { + /// Physical size in bytes. + fn len(&self) -> io::Result; + /// Read exactly `buf.len()` bytes at `offset`, zero-filling past the end. + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()>; + /// Write all of `buf` at `offset`, growing the store if needed. + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()>; + /// Resize the store, zero-filling any gap. + fn set_len(&mut self, len: u64) -> io::Result<()>; + /// Flush writes to durable storage. Buffers have nothing to flush. + fn sync(&mut self) -> io::Result<()> { + Ok(()) + } +} + +impl PageStore for File { + fn len(&self) -> io::Result { + Ok(self.metadata()?.len()) + } + + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + self.seek(SeekFrom::Start(offset))?; + self.read_exact(buf) + } + + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { + self.seek(SeekFrom::Start(offset))?; + self.write_all(buf) + } + + fn set_len(&mut self, len: u64) -> io::Result<()> { + File::set_len(self, len) + } + + fn sync(&mut self) -> io::Result<()> { + self.sync_all() + } +} + +/// A [`PageStore`] held entirely in memory. +#[cfg(any(feature = "turso", feature = "opfs"))] +#[derive(Default)] +pub(crate) struct MemPages(Vec); + +#[cfg(any(feature = "turso", feature = "opfs"))] +impl MemPages { + pub(crate) fn new() -> Self { + Self(Vec::new()) + } + + pub(crate) fn from_vec(bytes: Vec) -> Self { + Self(bytes) + } + + pub(crate) fn as_slice(&self) -> &[u8] { + &self.0 + } +} + +#[cfg(any(feature = "turso", feature = "opfs"))] +impl PageStore for MemPages { + fn len(&self) -> io::Result { + Ok(self.0.len() as u64) + } + + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let start = usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + let end = start + .checked_add(buf.len()) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + if start >= self.0.len() { + buf.fill(0); + return Ok(()); + } + let available = self.0.len() - start; + let n = available.min(buf.len()); + buf[..n].copy_from_slice(&self.0[start..start + n]); + buf[n..].fill(0); + let _ = end; + Ok(()) + } + + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { + let start = usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + let end = start + .checked_add(buf.len()) + .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; + if self.0.len() < end { + self.0.resize(end, 0); + } + self.0[start..end].copy_from_slice(buf); + Ok(()) + } + + fn set_len(&mut self, len: u64) -> io::Result<()> { + let len = usize::try_from(len).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + self.0.resize(len, 0); + Ok(()) + } + + fn sync(&mut self) -> io::Result<()> { + Ok(()) + } +} + diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 29acf55..bfcbe80 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -16,6 +16,7 @@ use zeroize::{Zeroize, Zeroizing}; use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_file}; use super::turso_common::TursoFile; +use super::turso_web::WebIo; use crate::error::KeyRingError; /// The cipher Turso uses to encrypt database pages. @@ -88,6 +89,8 @@ pub use ::turso::core; /// such as the Origin Private File System in a browser worker. pub struct TursoKeyring { file: TursoFile, + /// Set on keyrings whose database lives in memory, so it can be copied out. + web: Option>, } file_keyring!(TursoKeyring, file); @@ -99,7 +102,7 @@ impl TursoKeyring { if let Some(db_path) = file.db_path() { secure_file(db_path)?; } - Ok(Self { file }) + Ok(Self { file, web: None }) } /// Adopt an already-open Turso connection. @@ -128,6 +131,7 @@ impl TursoKeyring { pub fn from_connection(conn: Connection) -> Result { Ok(Self { file: TursoFile::adopt(conn)?, + web: None, }) } @@ -144,9 +148,49 @@ impl TursoKeyring { pub fn with_io(io: Arc, path: &str, params: &ConnectionParams) -> Result { Ok(Self { file: TursoFile::open_with(builder(params)?(path).with_io_impl(io))?, + web: None, }) } + /// Open a keyring whose database lives in process memory. + /// + /// Nothing reaches the filesystem, so this works in a browser. Copy the + /// database out with [`export`](Self::export) to persist it and reopen + /// with [`from_bytes`](Self::from_bytes). + pub fn in_memory(params: &ConnectionParams) -> Result { + let io = WebIo::in_memory(); + Self::open_web(Arc::clone(&io), "cryptex.db3", params).map(|k| Self { web: Some(io), ..k }) + } + + /// Reopen a keyring from an image produced by [`export`](Self::export). + pub fn from_bytes(bytes: &[u8], params: &ConnectionParams) -> Result { + let io = WebIo::restore(bytes)?; + Self::open_web(Arc::clone(&io), "cryptex.db3", params).map(|k| Self { web: Some(io), ..k }) + } + + fn open_web(io: Arc, path: &str, params: &ConnectionParams) -> Result { + let io: Arc = io; + // The image was already parsed, so the only thing left that can refuse + // the open is the key: an image written under another key looks like a + // corrupt one. Report both the way [`MemoryKeyring::import`] does. + Self::with_io(io, path, params).map_err(|_| KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring image".to_string(), + }) + } + + /// Copy the whole in-memory database into one encrypted blob. + /// + /// Fails for a keyring opened from a path or from a caller's connection: + /// the caller owns that storage, so it owns copying it. + pub fn export(&self) -> Result> { + self.web + .as_ref() + .ok_or_else(|| KeyRingError::GeneralError { + msg: "export is only available for an in-memory keyring".to_string(), + })? + .snapshot() + } + /// Re-encrypt the keyring with a new key (and optionally a different cipher). /// /// Consumes the keyring and returns it reopened under `new_params`. If @@ -157,7 +201,7 @@ impl TursoKeyring { if let Some(db_path) = file.db_path() { secure_file(db_path)?; } - Ok(Self { file }) + Ok(Self { file, web: None }) } } @@ -228,6 +272,39 @@ mod tests { assert!(!raw.windows(13).any(|w| w == b"SQLite format")); } + #[test] + fn in_memory_round_trips_through_an_image() { + let p = params("password=in_memory salt=1qaz2wsx3edc4rfv5tgb"); + let wrong = params("password=nope salt=1qaz2wsx3edc4rfv5tgb"); + + let image = { + let mut kr = TursoKeyring::in_memory(&p).unwrap(); + kr.set_secret("k1", b"value1").unwrap(); + kr.set_secret("shared", b"kept").unwrap(); + let image = kr.export().unwrap(); + assert!(!image.windows(6).any(|w| w == b"value1")); + image + }; + + let mut restored = TursoKeyring::from_bytes(&image, &p).unwrap(); + assert_eq!(restored.get_secret("k1").unwrap().0, b"value1"); + assert_eq!(restored.get_secret("shared").unwrap().0, b"kept"); + + assert!(matches!( + TursoKeyring::from_bytes(&image, &wrong), + Err(KeyRingError::AccessDenied { .. }) + )); + assert!(TursoKeyring::from_bytes(b"not a snapshot", &p).is_err()); + } + + #[test] + fn export_needs_an_in_memory_keyring() { + let dir = TestDir::new(".test-turso-export"); + let p = params("password=export_test salt=1qaz2wsx3edc4rfv5tgb"); + let kr = TursoKeyring::with_params(&p, dir.keyring_dir()).unwrap(); + assert!(kr.export().is_err()); + } + #[test] fn wrong_key_and_concurrent_open_fail() { let dir = TestDir::new(".test-turso-wrongkey"); diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index 3b8185f..b5090e7 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -231,6 +231,7 @@ impl TursoFile { /// Open through a caller-supplied [`Builder`], e.g. one carrying a custom /// Turso `IO`. No path is resolved and no lock file is created: the caller /// owns the storage. + #[cfg_attr(not(feature = "turso"), allow(dead_code))] pub(crate) fn open_with(builder: Builder) -> Result { Ok(Self { store: TursoStore::open(builder)?, @@ -240,6 +241,7 @@ impl TursoFile { /// Adopt an already-open connection. The keyring creates and owns its /// `secrets` table and leaves every other table alone. + #[cfg_attr(not(feature = "turso"), allow(dead_code))] pub(crate) fn adopt(conn: Connection) -> Result { Ok(Self { store: TursoStore::adopt(conn)?, diff --git a/src/keyring/turso_encrypted_io.rs b/src/keyring/turso_encrypted_io.rs index 89fe412..e686e0c 100644 --- a/src/keyring/turso_encrypted_io.rs +++ b/src/keyring/turso_encrypted_io.rs @@ -23,6 +23,7 @@ use std::sync::{Arc, Mutex, MutexGuard}; use super::file_common::{self, derive_key_32, file_keyring, private_open_options}; use super::page_cipher::{self, ActiveCipher}; +use super::page_store::PageStore; use super::turso_common::TursoFile; pub use super::cipher::CipherAlgorithm; @@ -112,14 +113,14 @@ impl TursoFileIo for EncryptedFile { fn pread(&self, pos: u64, c: Completion) -> TursoResult { let mut file = self.file()?; - let available = page_cipher::logical_size(&file) + let available = page_cipher::logical_size(&*file) .map_err(|e| io_error(e, "pread"))? .saturating_sub(pos); let read = { let buf = c.as_read().buf().as_mut_slice(); let n = buf.len().min(to_usize(available)?); self.cipher - .read_at(&mut file, to_usize(pos)?, &mut buf[..n]) + .read_at(&mut *file, to_usize(pos)?, &mut buf[..n]) .map_err(|e| io_error(e, "pread"))? }; c.complete(to_i32(read)?); @@ -136,7 +137,7 @@ impl TursoFileIo for EncryptedFile { } fn sync(&self, c: Completion, _sync_type: FileSyncType) -> TursoResult { - self.file()?.sync_all().map_err(|e| io_error(e, "sync"))?; + self.file()?.sync().map_err(|e| io_error(e, "sync"))?; c.complete(0); Ok(c) } @@ -146,7 +147,7 @@ impl TursoFileIo for EncryptedFile { } fn truncate(&self, len: u64, c: Completion) -> TursoResult { - page_cipher::truncate(&*self.file()?, to_usize(len)?) + page_cipher::truncate(&mut *self.file()?, to_usize(len)?) .map_err(|e| io_error(e, "truncate"))?; c.complete(0); Ok(c) diff --git a/src/keyring/turso_web.rs b/src/keyring/turso_web.rs new file mode 100644 index 0000000..86001f4 --- /dev/null +++ b/src/keyring/turso_web.rs @@ -0,0 +1,316 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! A Turso [`IO`] whose files live in process memory, for browsers and for +//! tests. +//! +//! Turso opens the database and its WAL as ordinary files. This backend keeps +//! each one in a [`PageStore`] buffer, so a whole database can be copied out +//! as one blob ([`WebIo::snapshot`]), stored somewhere durable such as +//! IndexedDB, and put back later ([`WebIo::restore`]). OPFS uses the same +//! shape with a synchronous access handle in place of the buffer. +//! +//! Reads and writes complete in place, so Turso never needs to park a thread — +//! which a wasm build cannot do. +//! +//! [`IO`]: ::turso::core::IO + +use super::page_store::{MemPages, PageStore}; +use ::turso::core::io::FileId; +use ::turso::core::io::FileSyncType; +use ::turso::core::{ + Buffer, Clock, Completion, File as TursoFileIo, IO, LimboError, MonotonicInstant, OpenFlags, + WallClockInstant, io_error, +}; +use crate::error::KeyRingError; +use crate::Result; +use std::collections::HashMap; +use std::sync::{Arc, Mutex, MutexGuard}; + +type TursoResult = std::result::Result; + +const SNAPSHOT_MAGIC: &[u8; 10] = b"CRYPTEX-IO"; +const SNAPSHOT_VERSION: u8 = 1; + +/// Files held by [`WebIo`], keyed by the path Turso opened them with. +pub(crate) struct WebIo { + files: Mutex>>, +} + +impl WebIo { + /// Create an empty IO backed by process memory. + pub(crate) fn in_memory() -> Arc { + Arc::new(Self { + files: Mutex::new(HashMap::new()), + }) + } + + /// Copy every file into one blob. + /// + /// Layout: `magic (10) | version (1) | count (u32 LE)` then, per file in + /// path order, `path_len (u32 LE) | path | len (u64 LE) | bytes`. + pub(crate) fn snapshot(&self) -> Result> { + let files = self.files()?; + let mut entries: Vec<(&String, &Arc)> = files.iter().collect(); + entries.sort_by(|a, b| a.0.cmp(b.0)); + + let mut out = Vec::new(); + out.extend_from_slice(SNAPSHOT_MAGIC); + out.push(SNAPSHOT_VERSION); + out.extend_from_slice(&(entries.len() as u32).to_le_bytes()); + for (path, file) in entries { + let store = file.store().map_err(|_| poisoned())?; + let size = store + .len() + .map_err(|e| KeyRingError::GeneralError { msg: e.to_string() })?; + out.extend_from_slice(&(path.len() as u32).to_le_bytes()); + out.extend_from_slice(path.as_bytes()); + out.extend_from_slice(&size.to_le_bytes()); + out.extend_from_slice(store.as_slice()); + } + Ok(out) + } + + /// Rebuild an IO from a blob produced by [`WebIo::snapshot`]. + pub(crate) fn restore(bytes: &[u8]) -> Result> { + let malformed = || KeyRingError::GeneralError { + msg: "the keyring image is not a cryptex database snapshot".to_string(), + }; + let mut rest = bytes; + if rest.len() < 11 || &rest[..10] != SNAPSHOT_MAGIC { + return Err(malformed()); + } + rest = &rest[10..]; + if rest[0] != SNAPSHOT_VERSION { + return Err(malformed()); + } + rest = &rest[1..]; + let (count, tail) = take::<4>(rest).ok_or_else(malformed)?; + rest = tail; + let mut files = HashMap::with_capacity(u32::from_le_bytes(count) as usize); + for _ in 0..u32::from_le_bytes(count) { + let (len, tail) = take::<4>(rest).ok_or_else(malformed)?; + rest = tail; + let path_len = u32::from_le_bytes(len) as usize; + if rest.len() < path_len { + return Err(malformed()); + } + let path = String::from_utf8(rest[..path_len].to_vec()).map_err(|_| malformed())?; + rest = &rest[path_len..]; + + let (len, tail) = take::<8>(rest).ok_or_else(malformed)?; + rest = tail; + let data_len = usize::try_from(u64::from_le_bytes(len)).map_err(|_| malformed())?; + if rest.len() < data_len { + return Err(malformed()); + } + let store = MemPages::from_vec(rest[..data_len].to_vec()); + rest = &rest[data_len..]; + files.insert(path, Arc::new(WebFile::new(store))); + } + Ok(Arc::new(Self { + files: Mutex::new(files), + })) + } + + fn files(&self) -> Result>>> { + self.files.lock().map_err(|_| poisoned()) + } +} + +fn poisoned() -> KeyRingError { + KeyRingError::GeneralError { + msg: "the in-memory database lock is poisoned".to_string(), + } +} + +fn take(bytes: &[u8]) -> Option<([u8; N], &[u8])> { + let head = bytes.get(..N)?; + let mut out = [0u8; N]; + out.copy_from_slice(head); + Some((out, &bytes[N..])) +} + +impl IO for WebIo { + fn open_file( + &self, + path: &str, + flags: OpenFlags, + _direct: bool, + ) -> TursoResult> { + let mut files = self + .files + .lock() + .map_err(|_| LimboError::InternalError("database lock poisoned".to_string()))?; + if let Some(file) = files.get(path) { + let existing: Arc = Arc::clone(file); + return Ok(existing); + } + if !flags.contains(OpenFlags::Create) { + return Err(io_error( + std::io::Error::from(std::io::ErrorKind::NotFound), + "open_file", + )); + } + let file = Arc::new(WebFile::new(MemPages::new())); + files.insert(path.to_string(), Arc::clone(&file)); + let opened: Arc = file; + Ok(opened) + } + + fn remove_file(&self, path: &str) -> TursoResult<()> { + let mut files = self + .files + .lock() + .map_err(|_| LimboError::InternalError("database lock poisoned".to_string()))?; + files.remove(path); + Ok(()) + } + + fn file_id(&self, path: &str) -> TursoResult { + Ok(FileId::from_path_hash(path)) + } + + fn is_memory(&self) -> bool { + true + } +} + +impl Clock for WebIo { + fn current_time_monotonic(&self) -> MonotonicInstant { + MonotonicInstant::from_nanos(monotonic_nanos()) + } + + fn current_time_wall_clock(&self) -> WallClockInstant { + wall_clock_now() + } +} + +/// Milliseconds since navigation start, from `performance.now()`. +/// +/// A worker has no `window`, so the value is read off the global object. +#[cfg(target_family = "wasm")] +fn performance_millis() -> Option { + use wasm_bindgen::{JsCast, JsValue}; + + let global = js_sys::global(); + let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance")).ok()?; + let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now")).ok()?; + let now: js_sys::Function = now.dyn_into().ok()?; + now.call0(&performance).ok()?.as_f64() +} + +#[cfg(target_family = "wasm")] +fn monotonic_nanos() -> u128 { + // The wall clock still moves forward if the page hides, and nanosecond + // resolution is wasted on a millisecond source. + let millis = performance_millis().unwrap_or_else(js_sys::Date::now); + (millis * 1_000_000.0) as u128 +} + +#[cfg(not(target_family = "wasm"))] +fn monotonic_nanos() -> u128 { + use std::sync::OnceLock; + use std::time::Instant; + + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos() +} + +#[cfg(target_family = "wasm")] +fn wall_clock_now() -> WallClockInstant { + let millis = js_sys::Date::now(); + let secs = (millis / 1000.0).floor(); + let micros = ((millis - secs * 1000.0) * 1000.0).round() as u32; + WallClockInstant { + secs: secs as i64, + micros: micros.min(999_999), + } +} + +#[cfg(not(target_family = "wasm"))] +fn wall_clock_now() -> WallClockInstant { + use std::time::{SystemTime, UNIX_EPOCH}; + + let since_epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + WallClockInstant { + secs: since_epoch.as_secs() as i64, + micros: since_epoch.subsec_micros(), + } +} + +struct WebFile { + store: Mutex, +} + +impl WebFile { + fn new(store: MemPages) -> Self { + Self { + store: Mutex::new(store), + } + } + + fn store(&self) -> TursoResult> { + self.store + .lock() + .map_err(|_| LimboError::InternalError("database file lock poisoned".to_string())) + } +} + +fn to_i32(n: usize) -> TursoResult { + i32::try_from(n).map_err(|_| LimboError::InternalError("I/O length overflows i32".into())) +} + +impl TursoFileIo for WebFile { + // A single opener per database is enforced by the caller, as in the + // browser storage and IndexedDB stores. + fn lock_file(&self, _exclusive: bool) -> TursoResult<()> { + Ok(()) + } + + fn unlock_file(&self) -> TursoResult<()> { + Ok(()) + } + + fn pread(&self, pos: u64, c: Completion) -> TursoResult { + let mut store = self.store()?; + let size = store.len().map_err(|e| io_error(e, "pread"))?; + let buf = c.as_read().buf().as_mut_slice(); + let n = (buf.len() as u64).min(size.saturating_sub(pos)) as usize; + store + .read_exact_at(pos, &mut buf[..n]) + .map_err(|e| io_error(e, "pread"))?; + c.complete(to_i32(n)?); + Ok(c) + } + + fn pwrite(&self, pos: u64, buffer: Arc, c: Completion) -> TursoResult { + let mut store = self.store()?; + store + .write_all_at(pos, buffer.as_slice()) + .map_err(|e| io_error(e, "pwrite"))?; + c.complete(to_i32(buffer.as_slice().len())?); + Ok(c) + } + + fn sync(&self, c: Completion, _sync_type: FileSyncType) -> TursoResult { + self.store()?.sync().map_err(|e| io_error(e, "sync"))?; + c.complete(0); + Ok(c) + } + + fn size(&self) -> TursoResult { + self.store()?.len().map_err(|e| io_error(e, "size")) + } + + fn truncate(&self, len: u64, c: Completion) -> TursoResult { + self.store()? + .set_len(len) + .map_err(|e| io_error(e, "truncate"))?; + c.complete(0); + Ok(c) + } +} From 0ce758adaba617c7a45761cb4660a192449e6043 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 14:50:30 -0500 Subject: [PATCH 04/18] Add browser storage: IndexedDB images, localStorage and OPFS IndexedDB keeps one encrypted image per keyring and takes a Web Lock named after it, so a second tab fails instead of overwriting the first. localStorage holds the same image for synchronous code that cannot await, and OPFS gives a worker a real file, opened through sync access handles so Turso never waits on a promise it cannot park for. --- Cargo.toml | 14 +- src/error.rs | 28 +++ src/keyring.rs | 8 + src/keyring/indexeddb.rs | 308 ++++++++++++++++++++++++++++ src/keyring/opfs.rs | 410 +++++++++++++++++++++++++++++++++++++ src/keyring/page_store.rs | 6 +- src/keyring/turso.rs | 13 ++ src/keyring/turso_web.rs | 60 +----- src/keyring/web_storage.rs | 201 ++++++++++++++++++ src/keyring/web_time.rs | 79 +++++++ src/lib.rs | 5 + 11 files changed, 1069 insertions(+), 63 deletions(-) create mode 100644 src/keyring/indexeddb.rs create mode 100644 src/keyring/opfs.rs create mode 100644 src/keyring/web_storage.rs create mode 100644 src/keyring/web_time.rs diff --git a/Cargo.toml b/Cargo.toml index 30ca8a3..f262d8b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -44,9 +44,15 @@ name = "cryptex" default = ["linux-secret-service", "macos-keychain", "windows-credentials"] file = ["dep:argon2", "dep:dirs", "dep:rusqlite", "rusqlite/bundled-sqlcipher-vendored-openssl"] memory = ["dep:argon2", "dep:chacha20poly1305", "dep:aes-gcm", "dep:getrandom"] -web-storage = ["memory", "dep:web-sys", "dep:wasm-bindgen"] -indexeddb = ["dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] -opfs = ["dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] +web-storage = [ + "memory", + "dep:web-sys", + "dep:wasm-bindgen", + "dep:wasm-bindgen-futures", + "dep:js-sys", +] +indexeddb = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] +opfs = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] js = [ "memory", "indexeddb", @@ -114,8 +120,10 @@ web-sys = { version = "0.3", optional = true, features = [ "IdbObjectStore", "IdbTransaction", "IdbTransactionMode", + "DomException", "IdbRequest", "FileSystemDirectoryHandle", + "FileSystemGetDirectoryOptions", "FileSystemFileHandle", "FileSystemGetFileOptions", "FileSystemSyncAccessHandle", diff --git a/src/error.rs b/src/error.rs index 00735fa..faf25f0 100644 --- a/src/error.rs +++ b/src/error.rs @@ -123,6 +123,34 @@ impl From for KeyRingError { } } +/// Browser APIs report failures as thrown JavaScript values. +#[cfg(any( + feature = "indexeddb", + feature = "opfs", + feature = "web-storage" +))] +#[cfg_attr( + docsrs, + doc(cfg(any( + feature = "indexeddb", + feature = "opfs", + feature = "web-storage" + ))) +)] +impl From for KeyRingError { + fn from(value: wasm_bindgen::JsValue) -> Self { + let detail = value + .as_string() + .or_else(|| { + js_sys::Reflect::get(&value, &wasm_bindgen::JsValue::from_str("message")) + .ok() + .and_then(|message| message.as_string()) + }) + .unwrap_or_else(|| format!("{value:?}")); + KeyRingError::GeneralError { msg: detail } + } +} + #[cfg(any(feature = "turso", feature = "turso-encrypted-io"))] #[cfg_attr( docsrs, diff --git a/src/keyring.rs b/src/keyring.rs index 9d173b5..18acdda 100644 --- a/src/keyring.rs +++ b/src/keyring.rs @@ -24,12 +24,16 @@ pub mod encrypted_vfs; pub mod file_common; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] pub mod kms; +#[cfg(feature = "indexeddb")] +pub mod indexeddb; #[cfg(all(target_os = "linux", feature = "linux-secret-service"))] pub mod linux; #[cfg(all(target_os = "macos", feature = "macos-keychain"))] pub mod macos; #[cfg(feature = "memory")] pub mod memory; +#[cfg(feature = "opfs")] +pub mod opfs; #[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))] mod page_cipher; #[cfg(any( @@ -51,6 +55,10 @@ mod turso_common; pub mod turso_encrypted_io; #[cfg(feature = "turso")] mod turso_web; +#[cfg(any(feature = "opfs", feature = "turso"))] +mod web_time; +#[cfg(feature = "web-storage")] +pub mod web_storage; #[cfg(all(target_os = "windows", feature = "windows-credentials"))] pub mod windows; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs new file mode 100644 index 0000000..bbf62ac --- /dev/null +++ b/src/keyring/indexeddb.rs @@ -0,0 +1,308 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Durable keyring images in IndexedDB, for browsers. +//! +//! A browser tab has no filesystem, so a keyring is persisted as one image: +//! the bytes [`TursoKeyring::export`](crate::turso::TursoKeyring::export) +//! produces. This module stores that image and takes an exclusive Web Lock +//! named after the keyring, so two tabs cannot open the same keyring at the +//! same time and overwrite each other. +//! +//! ```no_run +//! # use cryptex::indexeddb::SnapshotStore; +//! # async fn example() -> Result<(), Box> { +//! let store = SnapshotStore::open("settings").await?; +//! if let Some(image) = store.load().await? { +//! // pass the image to TursoKeyring::from_bytes +//! # let _ = image; +//! } +//! # Ok(()) +//! # } +//! ``` +//! +//! IndexedDB is per origin and readable by every script that runs on it, so +//! the image must stay encrypted: the key never leaves the password or raw +//! key the caller passes to the keyring. + +use js_sys::Reflect; +use wasm_bindgen::prelude::*; +use wasm_bindgen::{JsCast, JsValue}; +use wasm_bindgen_futures::JsFuture; +use web_sys::{IdbDatabase, IdbFactory, IdbRequest, IdbTransaction, IdbTransactionMode}; + +use crate::error::KeyRingError; +use crate::Result; + +/// Database holding every keyring image for this origin. +const DB_NAME: &str = "cryptex"; +/// Object store within [`DB_NAME`]. +const STORE_NAME: &str = "keyrings"; + +/// An IndexedDB-backed snapshot of one keyring. +/// +/// Opening takes the Web Lock `cryptex:`; it is held until the store is +/// dropped. If another tab holds it, [`open`](Self::open) fails with +/// `AccessDenied` instead of waiting. +pub struct SnapshotStore { + name: String, + db: IdbDatabase, + _hold: LockHold, +} + +impl SnapshotStore { + /// Open the store for `name`, taking the single-opener lock. + pub async fn open(name: &str) -> Result { + let hold = LockHold::acquire(&format!("cryptex:{name}")).await?; + let db = open_db().await?; + Ok(Self { + name: name.to_string(), + db, + _hold: hold, + }) + } + + /// The name this store was opened under. + pub fn name(&self) -> &str { + &self.name + } + + /// Read the stored image, if there is one. + pub async fn load(&self) -> Result>> { + let tx = self.transaction(IdbTransactionMode::Readonly)?; + let value = await_request(&tx.object_store(STORE_NAME)?.get(&JsValue::from_str(&self.name))?).await?; + drop(tx); + if value.is_undefined() || value.is_null() { + Ok(None) + } else { + Ok(Some(js_sys::Uint8Array::new(&value).to_vec())) + } + } + + /// Write an image, replacing any previous one. Returns once the + /// transaction has committed. + pub async fn save(&self, image: &[u8]) -> Result<()> { + let tx = self.transaction(IdbTransactionMode::Readwrite)?; + let bytes = js_sys::Uint8Array::from(image); + tx.object_store(STORE_NAME)? + .put_with_key(&bytes, &JsValue::from_str(&self.name))?; + await_transaction(&tx).await + } + + /// Remove the stored image. + pub async fn delete(&self) -> Result<()> { + let tx = self.transaction(IdbTransactionMode::Readwrite)?; + tx.object_store(STORE_NAME)? + .delete(&JsValue::from_str(&self.name))?; + await_transaction(&tx).await + } + + fn transaction(&self, mode: IdbTransactionMode) -> Result { + self.db + .transaction_with_str_and_mode(STORE_NAME, mode) + .map_err(js_error) + } +} + +/// The exclusive lock held by a [`SnapshotStore`], released on drop. +/// +/// The lock lives as long as the promise the callback returns, so dropping +/// this resolves that promise and lets the next tab in. +struct LockHold { + /// Resolves the promise the lock callback returned. + release: std::rc::Rc>>, + /// The promise itself: the lock is held until it settles. + _held: js_sys::Promise, + /// The callback, kept alive because the browser may still call it. + _callback: JsValue, +} + +impl LockHold { + async fn acquire(name: &str) -> Result { + let locks = Reflect::get(&navigator()?, &JsValue::from_str("locks")).map_err(js_error)?; + if locks.is_undefined() || locks.is_null() { + return Err(unsupported( + "this browser has no Web Locks API, so a keyring cannot be opened safely", + )); + } + let request: js_sys::Function = Reflect::get(&locks, &JsValue::from_str("request")) + .map_err(js_error)? + .dyn_into() + .map_err(|_| unsupported("the Web Locks API is not callable"))?; + + let options = js_sys::Object::new(); + Reflect::set(&options, &JsValue::from_str("ifAvailable"), &JsValue::TRUE).map_err(js_error)?; + + // `release` settles the promise the callback returns, ending the lock. + let release: std::rc::Rc>> = + std::rc::Rc::new(std::cell::RefCell::new(None)); + let held = js_sys::Promise::new(&mut { + let release = std::rc::Rc::clone(&release); + move |resolve, _reject| *release.borrow_mut() = Some(resolve) + }); + + // Resolved once the callback runs, whether or not it got the lock. + let signalled: std::rc::Rc>> = + std::rc::Rc::new(std::cell::RefCell::new(None)); + let signal = js_sys::Promise::new(&mut { + let signalled = std::rc::Rc::clone(&signalled); + move |resolve, _reject| *signalled.borrow_mut() = Some(resolve) + }); + + let denied = std::rc::Rc::new(std::cell::Cell::new(false)); + let callback = { + let denied = std::rc::Rc::clone(&denied); + let held = held.clone(); + let signalled = std::rc::Rc::clone(&signalled); + Closure:: JsValue>::once_into_js(move |lock: JsValue| { + if let Some(resolve) = signalled.borrow_mut().take() { + let _ = resolve.call0(&JsValue::NULL); + } + if lock.is_null() || lock.is_undefined() { + denied.set(true); + JsValue::UNDEFINED + } else { + JsValue::from(held.clone()) + } + }) + }; + + let request_promise: js_sys::Promise = request + .call3( + &locks, + &JsValue::from_str(name), + &options, + callback.unchecked_ref(), + ) + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + // Wait for whichever happens first: the callback runs, or the request + // itself fails. A granted lock keeps its request pending, so racing is + // what makes this usable at all. + let signals = js_sys::Array::of2(&signal, &request_promise); + JsFuture::from(js_sys::Promise::race(signals.as_ref())) + .await + .map_err(js_error)?; + + if denied.get() { + return Err(KeyRingError::AccessDenied { + msg: format!("the keyring '{name}' is open in another tab"), + }); + } + Ok(Self { + release, + _held: held, + _callback: callback, + }) + } +} + +impl Drop for LockHold { + fn drop(&mut self) { + if let Some(release) = self.release.borrow_mut().take() { + let _ = release.call0(&JsValue::NULL); + } + } +} + +async fn open_db() -> Result { + let factory: IdbFactory = Reflect::get(&navigator()?, &JsValue::from_str("indexedDB")) + .map_err(js_error)? + .dyn_into() + .map_err(|_| unsupported("this browser has no IndexedDB"))?; + let request = factory + .open_with_u32(DB_NAME, 1) + .map_err(js_error)?; + + // Create the object store the first time the database is opened. + let upgrade_request = request.clone(); + let upgrade = Closure::::once_into_js(move |_event: JsValue| { + if let Some(db) = upgrade_request + .result() + .ok() + .and_then(|db| db.dyn_into::().ok()) + { + let _ = db.create_object_store(STORE_NAME); + } + }); + request.set_onupgradeneeded(Some(upgrade.unchecked_ref())); + + let db = await_request(&request).await?; + db.dyn_into::().map_err(js_error) +} + +/// The global object: `window` in a page, the worker scope in a worker. +fn navigator() -> Result { + let global = js_sys::global(); + // Workers expose `navigator` too, so this works in both contexts. + Reflect::get(&global, &JsValue::from_str("navigator")) + .map_err(js_error) + .and_then(|navigator| { + if navigator.is_undefined() { + Err(unsupported("no navigator: not a browser context")) + } else { + Ok(navigator) + } + }) +} + +/// Resolve a request's promise with `request.result`, rejecting on error. +async fn await_request(request: &IdbRequest) -> Result { + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let on_success = { + let request = request.clone(); + let resolve = resolve.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let value = request.result().unwrap_or(JsValue::NULL); + let _ = resolve.call1(&JsValue::NULL, &value); + }) + }; + let on_error = { + let request = request.clone(); + let reject = reject.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let err = request.error().ok().flatten().map(JsValue::from).unwrap_or(JsValue::NULL); + let _ = reject.call1(&JsValue::NULL, &err); + }) + }; + request.set_onsuccess(Some(on_success.unchecked_ref())); + request.set_onerror(Some(on_error.unchecked_ref())); + }); + JsFuture::from(promise).await.map_err(js_error) +} + +/// Wait for a transaction to commit. +async fn await_transaction(tx: &IdbTransaction) -> Result<()> { + let promise = js_sys::Promise::new(&mut |resolve, reject| { + let on_complete = { + let resolve = resolve.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let _ = resolve.call0(&JsValue::NULL); + }) + }; + let on_error = { + let tx = tx.clone(); + let reject = reject.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let err = tx.error().map(JsValue::from).unwrap_or(JsValue::NULL); + let _ = reject.call1(&JsValue::NULL, &err); + }) + }; + tx.set_oncomplete(Some(on_complete.unchecked_ref())); + tx.set_onerror(Some(on_error.unchecked_ref())); + }); + JsFuture::from(promise).await.map(|_| ()).map_err(js_error) +} + +fn js_error(value: JsValue) -> KeyRingError { + KeyRingError::from(value) +} + +fn unsupported(msg: &str) -> KeyRingError { + KeyRingError::GeneralError { + msg: msg.to_string(), + } +} diff --git a/src/keyring/opfs.rs b/src/keyring/opfs.rs new file mode 100644 index 0000000..86ddb12 --- /dev/null +++ b/src/keyring/opfs.rs @@ -0,0 +1,410 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Origin Private File System storage for a Turso keyring. +//! +//! OPFS is a real filesystem owned by the origin. Its synchronous access +//! handles are the only way to read and write files without awaiting every +//! call, and browsers only hand them out inside a worker — which is exactly +//! where a keyring belongs, since deriving a key with Argon2 would otherwise +//! freeze the page. +//! +//! ```no_run +//! # use cryptex::turso::TursoKeyring; +//! # use cryptex::KeyRing; +//! # async fn example() -> Result<(), Box> { +//! let params = "password=mysecret salt=0okm9ijn8uhb7ygv".parse()?; +//! let mut keyring = TursoKeyring::open_opfs(¶ms, "settings").await?; +//! keyring.set_secret("api-token", b"secret")?; +//! # Ok(()) +//! # } +//! ``` +//! +//! Files live under `cryptex/` in the origin's private filesystem, as +//! `.db3` plus the `.db3-wal` Turso keeps next to it. Holding the +//! sync access handle is itself exclusive: a second tab or worker that tries +//! to open the same keyring gets an error from the browser instead of +//! corrupting the file, so no separate lock file is needed. +//! +//! Like every browser store, OPFS is readable by any script on the origin, so +//! the pages stay encrypted and the key never leaves the password. + +use super::page_store::PageStore; +use super::web_time::WebClock; +use ::turso::core::io::FileId; +use ::turso::core::{Clock, File as TursoFileIo, LimboError, MonotonicInstant, WallClockInstant, io_error}; +use crate::error::KeyRingError; +use crate::Result; +use std::cell::{Cell, RefCell}; +use std::collections::HashMap; +use std::io; +use std::sync::{Arc, Mutex, MutexGuard}; +use wasm_bindgen::JsCast; +use wasm_bindgen_futures::JsFuture; +use web_sys::{ + FileSystemDirectoryHandle, FileSystemGetDirectoryOptions, FileSystemGetFileOptions, + FileSystemReadWriteOptions, FileSystemSyncAccessHandle, +}; + +/// Directory inside the origin's private filesystem. +const DIRECTORY: &str = "cryptex"; + +thread_local! { + /// Handles are `!Send`, so they live here and the store keeps only an id. + /// Wasm runs one thread, so a thread-local is the whole registry. + static HANDLES: RefCell> = + RefCell::new(HashMap::new()); + static NEXT_ID: Cell = const { Cell::new(1) }; +} + +/// A [`PageStore`] over one OPFS file's synchronous access handle. +pub(crate) struct OpfsPages { + id: u32, +} + +impl OpfsPages { + /// Open (creating if needed) `name` inside the cryptex directory. + async fn open(name: &str) -> Result { + let directory = open_directory().await?; + let options = FileSystemGetFileOptions::new(); + options.set_create(true); + let handle: web_sys::FileSystemFileHandle = JsFuture::from( + directory.get_file_handle_with_options(name, &options), + ) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + let access: FileSystemSyncAccessHandle = + JsFuture::from(handle.create_sync_access_handle()) + .await + .map_err(|e| { + KeyRingError::AccessDenied { + msg: format!( + "unable to take exclusive access to {name} in OPFS (is another tab or worker using it?): {}", + js_message(e) + ), + } + })? + .dyn_into() + .map_err(js_error)?; + + let id = NEXT_ID.with(|next| { + let id = next.get(); + next.set(id.wrapping_add(1)); + id + }); + HANDLES.with(|handles| handles.borrow_mut().insert(id, access)); + Ok(Self { id }) + } + + /// Release the handle, closing the file. + pub(crate) fn close(&self) { + if let Some(handle) = HANDLES.with(|handles| handles.borrow_mut().remove(&self.id)) { + handle.close(); + } + } + + fn with_handle( + &self, + op: &str, + f: impl FnOnce(&FileSystemSyncAccessHandle) -> std::result::Result, + ) -> io::Result { + HANDLES.with(|handles| { + let handles = handles.borrow(); + let handle = handles.get(&self.id).ok_or_else(|| { + io::Error::other(format!("the OPFS handle is closed, cannot {op}")) + })?; + f(handle).map_err(|e| io::Error::other(js_message(e))) + }) + } +} + +impl PageStore for OpfsPages { + fn len(&self) -> io::Result { + self.with_handle("size the file", |handle| handle.get_size()) + .map(|size| size as u64) + } + + fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { + let mut filled = 0; + while filled < buf.len() { + let options = FileSystemReadWriteOptions::new(); + options.set_at((offset as usize + filled) as f64); + let read = self.with_handle("read", |handle| { + handle.read_with_u8_array_and_options(&mut buf[filled..], &options) + })? as usize; + if read == 0 { + // Past the end of the file: zero-fill, like a sparse file. + buf[filled..].fill(0); + return Ok(()); + } + filled += read; + } + Ok(()) + } + + fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { + let mut written = 0; + while written < buf.len() { + let options = FileSystemReadWriteOptions::new(); + options.set_at((offset as usize + written) as f64); + let n = self.with_handle("write", |handle| { + handle.write_with_u8_array_and_options(&buf[written..], &options) + })? as usize; + if n == 0 { + return Err(io::Error::other("OPFS accepted no bytes")); + } + written += n; + } + Ok(()) + } + + fn set_len(&mut self, len: u64) -> io::Result<()> { + self.with_handle("resize the file", |handle| { + handle.truncate_with_f64(len as f64) + }) + } + + fn sync(&mut self) -> io::Result<()> { + self.with_handle("flush the file", |handle| handle.flush()) + } +} + +/// The Turso [`IO`](::turso::core::IO) backed by OPFS. +/// +/// Both files Turso needs are opened up front, because a sync access handle is +/// obtained asynchronously: `open_file` itself cannot await. +pub(crate) struct OpfsIo { + files: HashMap>, +} + +impl OpfsIo { + /// Open `.db3` and its WAL under `cryptex/`. + pub(crate) async fn open(name: &str) -> Result { + let db = format!("{name}.db3"); + let wal = format!("{db}-wal"); + let mut files = HashMap::new(); + for path in [db, wal] { + let pages = OpfsPages::open(&path).await?; + files.insert(path, Arc::new(OpfsFile::new(pages))); + } + Ok(Self { files }) + } + + /// Flush both files to disk and release their handles. + pub(crate) fn close(&mut self) { + for file in self.files.values() { + file.close(); + } + self.files.clear(); + } +} + +impl Drop for OpfsIo { + fn drop(&mut self) { + self.close(); + } +} + +impl Clock for OpfsIo { + fn current_time_monotonic(&self) -> MonotonicInstant { + WebClock.current_time_monotonic() + } + + fn current_time_wall_clock(&self) -> WallClockInstant { + WebClock.current_time_wall_clock() + } +} + +impl ::turso::core::IO for OpfsIo { + fn open_file( + &self, + path: &str, + _flags: ::turso::core::OpenFlags, + _direct: bool, + ) -> std::result::Result, LimboError> { + // Only the database and its WAL are ever opened: the handle for each + // had to exist before Turso asked, so an unknown path is a bug in the + // caller's configuration, not a file to create. + match self.files.get(path) { + Some(file) => { + let file: Arc = Arc::clone(file); + Ok(file) + } + None => Err(LimboError::InternalError(format!( + "the OPFS keyring did not prepare '{path}'; it opens only the database and its WAL" + ))), + } + } + + fn remove_file(&self, _path: &str) -> std::result::Result<(), LimboError> { + Err(LimboError::InternalError( + "an OPFS keyring is removed through the file system, not Turso".to_string(), + )) + } + + fn is_memory(&self) -> bool { + false + } + + fn file_id(&self, path: &str) -> std::result::Result { + Ok(FileId::from_path_hash(path)) + } +} + +/// The Turso file view of one prepared OPFS file. +struct OpfsFile { + store: Mutex, +} + +impl OpfsFile { + fn new(pages: OpfsPages) -> Self { + Self { + store: Mutex::new(pages), + } + } + + /// Flush and close the handle. The store stays usable but fails every call. + fn close(&self) { + if let Ok(mut store) = self.store.lock() { + let _ = store.sync(); + store.close(); + } + } + + fn store(&self) -> std::result::Result, LimboError> { + self.store + .lock() + .map_err(|_| LimboError::InternalError("OPFS file lock poisoned".to_string())) + } +} + +fn to_i32(n: usize) -> std::result::Result { + i32::try_from(n).map_err(|_| LimboError::InternalError("I/O length overflows i32".into())) +} + +impl TursoFileIo for OpfsFile { + // The sync access handle is already exclusive. + fn lock_file(&self, _exclusive: bool) -> std::result::Result<(), LimboError> { + Ok(()) + } + + fn unlock_file(&self) -> std::result::Result<(), LimboError> { + Ok(()) + } + + fn pread( + &self, + pos: u64, + c: ::turso::core::Completion, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + let mut store = self.store()?; + let size = store.len().map_err(|e| io_error(e, "pread"))?; + let buf = c.as_read().buf().as_mut_slice(); + let n = (buf.len() as u64).min(size.saturating_sub(pos)) as usize; + store + .read_exact_at(pos, &mut buf[..n]) + .map_err(|e| io_error(e, "pread"))?; + c.complete(to_i32(n)?); + Ok(c) + } + + fn pwrite( + &self, + pos: u64, + buffer: Arc<::turso::core::Buffer>, + c: ::turso::core::Completion, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + let mut store = self.store()?; + store + .write_all_at(pos, buffer.as_slice()) + .map_err(|e| io_error(e, "pwrite"))?; + c.complete(to_i32(buffer.as_slice().len())?); + Ok(c) + } + + fn sync( + &self, + c: ::turso::core::Completion, + _sync_type: ::turso::core::io::FileSyncType, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + self.store()?.sync().map_err(|e| io_error(e, "sync"))?; + c.complete(0); + Ok(c) + } + + fn size(&self) -> std::result::Result { + self.store()?.len().map_err(|e| io_error(e, "size")) + } + + fn truncate( + &self, + len: u64, + c: ::turso::core::Completion, + ) -> std::result::Result<::turso::core::Completion, LimboError> { + self.store()? + .set_len(len) + .map_err(|e| io_error(e, "truncate"))?; + c.complete(0); + Ok(c) + } +} + +async fn open_directory() -> Result { + let navigator = + js_sys::Reflect::get(&js_sys::global(), &wasm_bindgen::JsValue::from_str("navigator")) + .map_err(js_error)?; + let storage = js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("storage")) + .map_err(js_error)?; + if storage.is_undefined() { + return Err(unsupported( + "this browser has no Storage Manager API, so OPFS is unavailable", + )); + } + let get_directory = js_sys::Reflect::get( + &storage, + &wasm_bindgen::JsValue::from_str("getDirectory"), + ) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?; + let root: FileSystemDirectoryHandle = JsFuture::from( + get_directory + .call0(&storage) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?, + ) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + let options = FileSystemGetDirectoryOptions::new(); + options.set_create(true); + let directory = JsFuture::from( + root.get_directory_handle_with_options(DIRECTORY, &options), + ) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + Ok(directory) +} + +fn js_error(value: wasm_bindgen::JsValue) -> KeyRingError { + KeyRingError::from(value) +} + +fn js_message(value: wasm_bindgen::JsValue) -> String { + KeyRingError::from(value).as_str() +} + +fn unsupported(msg: &str) -> KeyRingError { + KeyRingError::GeneralError { + msg: msg.to_string(), + } +} diff --git a/src/keyring/page_store.rs b/src/keyring/page_store.rs index dc13ce9..2641bbd 100644 --- a/src/keyring/page_store.rs +++ b/src/keyring/page_store.rs @@ -58,11 +58,11 @@ impl PageStore for File { } /// A [`PageStore`] held entirely in memory. -#[cfg(any(feature = "turso", feature = "opfs"))] +#[cfg(feature = "turso")] #[derive(Default)] pub(crate) struct MemPages(Vec); -#[cfg(any(feature = "turso", feature = "opfs"))] +#[cfg(feature = "turso")] impl MemPages { pub(crate) fn new() -> Self { Self(Vec::new()) @@ -77,7 +77,7 @@ impl MemPages { } } -#[cfg(any(feature = "turso", feature = "opfs"))] +#[cfg(feature = "turso")] impl PageStore for MemPages { fn len(&self) -> io::Result { Ok(self.0.len() as u64) diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index bfcbe80..664ab0d 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -16,6 +16,8 @@ use zeroize::{Zeroize, Zeroizing}; use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_file}; use super::turso_common::TursoFile; +#[cfg(feature = "opfs")] +use super::opfs::OpfsIo; use super::turso_web::WebIo; use crate::error::KeyRingError; @@ -178,6 +180,17 @@ impl TursoKeyring { }) } + /// Open (or create) the keyring in the origin private file system. + /// + /// Only available in a browser worker: OPFS sync access handles exist + /// nowhere else. The database and its WAL live under `cryptex/.db3`. + #[cfg(feature = "opfs")] + pub async fn open_opfs(params: &ConnectionParams, name: &str) -> Result { + let io: Arc = Arc::new(OpfsIo::open(name).await?); + let keyring = Self::with_io(io, &format!("{name}.db3"), params)?; + Ok(keyring) + } + /// Copy the whole in-memory database into one encrypted blob. /// /// Fails for a keyring opened from a path or from a caller's connection: diff --git a/src/keyring/turso_web.rs b/src/keyring/turso_web.rs index 86001f4..92c977a 100644 --- a/src/keyring/turso_web.rs +++ b/src/keyring/turso_web.rs @@ -17,6 +17,7 @@ //! [`IO`]: ::turso::core::IO use super::page_store::{MemPages, PageStore}; +use super::web_time::WebClock; use ::turso::core::io::FileId; use ::turso::core::io::FileSyncType; use ::turso::core::{ @@ -179,66 +180,11 @@ impl IO for WebIo { impl Clock for WebIo { fn current_time_monotonic(&self) -> MonotonicInstant { - MonotonicInstant::from_nanos(monotonic_nanos()) + WebClock.current_time_monotonic() } fn current_time_wall_clock(&self) -> WallClockInstant { - wall_clock_now() - } -} - -/// Milliseconds since navigation start, from `performance.now()`. -/// -/// A worker has no `window`, so the value is read off the global object. -#[cfg(target_family = "wasm")] -fn performance_millis() -> Option { - use wasm_bindgen::{JsCast, JsValue}; - - let global = js_sys::global(); - let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance")).ok()?; - let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now")).ok()?; - let now: js_sys::Function = now.dyn_into().ok()?; - now.call0(&performance).ok()?.as_f64() -} - -#[cfg(target_family = "wasm")] -fn monotonic_nanos() -> u128 { - // The wall clock still moves forward if the page hides, and nanosecond - // resolution is wasted on a millisecond source. - let millis = performance_millis().unwrap_or_else(js_sys::Date::now); - (millis * 1_000_000.0) as u128 -} - -#[cfg(not(target_family = "wasm"))] -fn monotonic_nanos() -> u128 { - use std::sync::OnceLock; - use std::time::Instant; - - static EPOCH: OnceLock = OnceLock::new(); - EPOCH.get_or_init(Instant::now).elapsed().as_nanos() -} - -#[cfg(target_family = "wasm")] -fn wall_clock_now() -> WallClockInstant { - let millis = js_sys::Date::now(); - let secs = (millis / 1000.0).floor(); - let micros = ((millis - secs * 1000.0) * 1000.0).round() as u32; - WallClockInstant { - secs: secs as i64, - micros: micros.min(999_999), - } -} - -#[cfg(not(target_family = "wasm"))] -fn wall_clock_now() -> WallClockInstant { - use std::time::{SystemTime, UNIX_EPOCH}; - - let since_epoch = SystemTime::now() - .duration_since(UNIX_EPOCH) - .unwrap_or_default(); - WallClockInstant { - secs: since_epoch.as_secs() as i64, - micros: since_epoch.subsec_micros(), + WebClock.current_time_wall_clock() } } diff --git a/src/keyring/web_storage.rs b/src/keyring/web_storage.rs new file mode 100644 index 0000000..c19c696 --- /dev/null +++ b/src/keyring/web_storage.rs @@ -0,0 +1,201 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! A keyring kept in browser `localStorage`. +//! +//! The whole keyring is an encrypted image ([`MemoryKeyring::export`]) that is +//! rewritten whenever a secret changes. It is the simplest browser backend: +//! no worker and no asynchronous API, so it fits code that must stay +//! synchronous, such as an `onclick` handler. +//! +//! ```no_run +//! # use cryptex::web_storage::WebStorageKeyring; +//! # use cryptex::KeyRing; +//! let mut keyring = WebStorageKeyring::with_params( +//! &"password=mysecret salt=0okm9ijn8uhb7ygv".parse()?, +//! Some("settings"), +//! )?; +//! keyring.set_secret("api-token", b"secret")?; +//! # Ok::<(), Box>(()) +//! ``` +//! +//! `localStorage` belongs to the page, not to the worker: a web worker has no +//! `localStorage` at all. Use the [`indexeddb`](crate::indexeddb) store from a +//! worker instead. +//! +//! Every script on the origin can read `localStorage`, and browsers evict it +//! under storage pressure unless the site has been granted persistent storage +//! ([`request_persistent_storage`]). The image is encrypted, so what a script +//! gets is ciphertext. + +use super::cipher::CipherAlgorithm; +use super::file_common; +use super::memory::MemoryKeyring; +use crate::error::KeyRingError; +use wasm_bindgen::JsCast; +use crate::KeyRingSecret; +use crate::{DynKeyRing, NewKeyRing, Result}; + +/// Connection parameters for [`WebStorageKeyring`]. +pub type ConnectionParams = file_common::ConnectionParams; + +/// `localStorage` key used when no name is given. +pub const DEFAULT_NAME: &str = "cryptex"; + +/// A keyring whose image lives in `localStorage`. +pub struct WebStorageKeyring { + inner: MemoryKeyring, + /// `localStorage` key holding the image. + entry: String, +} + +impl WebStorageKeyring { + /// Open the keyring called `name` (default [`DEFAULT_NAME`]), creating it + /// on first use. + /// + /// A stored image is decrypted with the password or key in `params`; a + /// wrong one returns [`KeyRingError::AccessDenied`]. + pub fn with_params(params: &ConnectionParams, name: Option<&str>) -> Result { + let entry = entry_name(name); + let storage = storage()?; + let inner = match storage.get_item(&entry).map_err(js_error)? { + Some(encoded) => { + let blob = hex::decode(encoded).map_err(|_| invalid_blob())?; + MemoryKeyring::import(&blob, password_or_key(params)) + } + None => MemoryKeyring::with_params(params), + }?; + Ok(Self { inner, entry }) + } + + /// The `localStorage` key this keyring is stored under. + pub fn entry(&self) -> &str { + &self.entry + } + + /// Copy the encrypted image out, e.g. to move it to another backend. + pub fn export(&self) -> Result> { + self.inner.export() + } + + /// Re-encrypt under new connection parameters and store the result. + pub fn rekey(&mut self, params: &ConnectionParams) -> Result<()> { + self.inner.rekey(params)?; + self.persist() + } + + /// The cipher the stored image is sealed with. + pub fn cipher(&self) -> CipherAlgorithm { + self.inner.cipher() + } + + /// Remove the stored image, leaving this keyring's contents in memory. + pub fn forget(&self) -> Result<()> { + storage()?.remove_item(&self.entry).map_err(js_error) + } + + fn persist(&self) -> Result<()> { + let image = self.inner.export()?; + storage()? + .set_item(&self.entry, &hex::encode(image)) + .map_err(|e| match js_error(e) { + KeyRingError::GeneralError { msg } => KeyRingError::GeneralError { + msg: format!("unable to store the keyring in localStorage: {msg}"), + }, + other => other, + }) + } +} + +impl DynKeyRing for WebStorageKeyring { + fn get_secret(&mut self, id: &str) -> Result { + self.inner.get_secret(id) + } + + fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> { + self.inner.set_secret(id, secret)?; + self.persist() + } + + fn delete_secret(&mut self, id: &str) -> Result<()> { + self.inner.delete_secret(id)?; + self.persist() + } +} + +impl NewKeyRing for WebStorageKeyring { + fn new>(lock_key: S) -> Result { + let params = lock_key.as_ref().parse::()?; + Self::with_params(¶ms, None) + } +} + +fn entry_name(name: Option<&str>) -> String { + format!("cryptex:{}", name.unwrap_or(DEFAULT_NAME)) +} + +fn password_or_key(params: &ConnectionParams) -> &[u8] { + if params.key.is_empty() { + ¶ms.password + } else { + ¶ms.key + } +} + +/// Ask the browser not to evict this origin's storage under pressure. +/// +/// Browsers grant this silently, prompt, or refuse; the answer is returned as +/// given. +pub async fn request_persistent_storage() -> Result { + let storage_manager = js_sys::Reflect::get( + &js_sys::global(), + &wasm_bindgen::JsValue::from_str("navigator"), + ) + .ok() + .and_then(|navigator| { + js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("storage")).ok() + }) + .ok_or_else(|| KeyRingError::GeneralError { + msg: "this browser has no Storage Manager API".to_string(), + })?; + let persist = js_sys::Reflect::get(&storage_manager, &wasm_bindgen::JsValue::from_str("persist")) + .map_err(js_error)? + .dyn_into::() + .map_err(|_| KeyRingError::GeneralError { + msg: "this browser cannot persist storage".to_string(), + })?; + let granted = persist + .call0(&storage_manager) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?; + let value = wasm_bindgen_futures::JsFuture::from(granted) + .await + .map_err(js_error)?; + Ok(value.as_bool().unwrap_or(false)) +} + +fn storage() -> Result { + let window = web_sys::window().ok_or_else(|| KeyRingError::GeneralError { + msg: "localStorage is not available here: it exists only on a page, not in a worker" + .to_string(), + })?; + window + .local_storage() + .map_err(js_error)? + .ok_or_else(|| KeyRingError::GeneralError { + msg: "this browser blocks localStorage for the origin; cookies or private mode may be disabled" + .to_string(), + }) +} + +fn js_error(value: wasm_bindgen::JsValue) -> KeyRingError { + KeyRingError::from(value) +} + +fn invalid_blob() -> KeyRingError { + KeyRingError::AccessDenied { + msg: "the stored keyring is corrupt: its image could not be decoded".to_string(), + } +} diff --git a/src/keyring/web_time.rs b/src/keyring/web_time.rs new file mode 100644 index 0000000..793d227 --- /dev/null +++ b/src/keyring/web_time.rs @@ -0,0 +1,79 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Clocks for Turso I/O backends that run in a browser. +//! +//! Turso's own clock calls `Instant::now`, which panics on +//! `wasm32-unknown-unknown`: the platform has no monotonic clock behind it. +//! `performance.now()` is the closest equivalent and, unlike `Date.now()`, +//! only moves forward. + +use ::turso::core::{Clock, MonotonicInstant, WallClockInstant}; + +/// A [`Clock`] backed by the JavaScript runtime. +pub(crate) struct WebClock; + +impl Clock for WebClock { + fn current_time_monotonic(&self) -> MonotonicInstant { + MonotonicInstant::from_nanos(monotonic_nanos()) + } + + fn current_time_wall_clock(&self) -> WallClockInstant { + wall_clock_now() + } +} + +/// Milliseconds since the time origin, from `performance.now()`. +/// +/// A worker has no `window`, so the value is read off the global object. +#[cfg(target_family = "wasm")] +fn performance_millis() -> Option { + use wasm_bindgen::{JsCast, JsValue}; + + let global = js_sys::global(); + let performance = js_sys::Reflect::get(&global, &JsValue::from_str("performance")).ok()?; + let now = js_sys::Reflect::get(&performance, &JsValue::from_str("now")).ok()?; + let now: js_sys::Function = now.dyn_into().ok()?; + now.call0(&performance).ok()?.as_f64() +} + +#[cfg(target_family = "wasm")] +fn monotonic_nanos() -> u128 { + // Fall back to the wall clock where `performance` is missing. + let millis = performance_millis().unwrap_or_else(js_sys::Date::now); + (millis * 1_000_000.0) as u128 +} + +#[cfg(not(target_family = "wasm"))] +fn monotonic_nanos() -> u128 { + use std::sync::OnceLock; + use std::time::Instant; + + static EPOCH: OnceLock = OnceLock::new(); + EPOCH.get_or_init(Instant::now).elapsed().as_nanos() +} + +#[cfg(target_family = "wasm")] +fn wall_clock_now() -> WallClockInstant { + let millis = js_sys::Date::now(); + let secs = (millis / 1000.0).floor(); + let micros = ((millis - secs * 1000.0) * 1000.0).round() as u32; + WallClockInstant { + secs: secs as i64, + micros: micros.min(999_999), + } +} + +#[cfg(not(target_family = "wasm"))] +fn wall_clock_now() -> WallClockInstant { + use std::time::{SystemTime, UNIX_EPOCH}; + + let since_epoch = SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default(); + WallClockInstant { + secs: since_epoch.as_secs() as i64, + micros: since_epoch.subsec_micros(), + } +} diff --git a/src/lib.rs b/src/lib.rs index c880c09..dc28cd1 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -51,7 +51,12 @@ pub use keyring::linux; pub use keyring::macos; #[cfg(feature = "memory")] #[cfg_attr(docsrs, doc(cfg(feature = "memory")))] +#[cfg(feature = "indexeddb")] +pub use keyring::indexeddb; +#[cfg(feature = "memory")] pub use keyring::memory; +#[cfg(feature = "web-storage")] +pub use keyring::web_storage; #[cfg(feature = "file")] #[cfg_attr(docsrs, doc(cfg(feature = "file")))] pub use keyring::sqlcipher; From 0ac2829fcf5e062930615bf9d82b7f7ed9b0893a Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 14:53:14 -0500 Subject: [PATCH 05/18] Expose the keyring to JavaScript Keyring.open picks a backend (a Turso database or a plain memory image) and a store (IndexedDB, localStorage, OPFS or none), so a page can keep secrets without knowing which of them it needs. set and delete resolve once the image reached storage; export copies it out. Also add a browser example: IndexedDB from the page, OPFS from a worker. --- Cargo.toml | 3 + examples/web/index.html | 93 ++++++++ examples/web/main.js | 104 +++++++++ examples/web/worker.js | 64 ++++++ src/keyring/turso.rs | 12 ++ src/keyring/turso_common.rs | 5 + src/keyring/web_storage.rs | 78 +++++-- src/lib.rs | 3 + src/wasm.rs | 416 ++++++++++++++++++++++++++++++++++++ 9 files changed, 757 insertions(+), 21 deletions(-) create mode 100644 examples/web/index.html create mode 100644 examples/web/main.js create mode 100644 examples/web/worker.js create mode 100644 src/wasm.rs diff --git a/Cargo.toml b/Cargo.toml index f262d8b..6ed8d1e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -55,7 +55,10 @@ indexeddb = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futu opfs = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] js = [ "memory", + "web-storage", "indexeddb", + "opfs", + "turso", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", diff --git a/examples/web/index.html b/examples/web/index.html new file mode 100644 index 0000000..df53d34 --- /dev/null +++ b/examples/web/index.html @@ -0,0 +1,93 @@ + + + + + + cryptex in the browser + + + +

cryptex in the browser

+

+ The keyring is a Turso database kept in IndexedDB. Everything you store is + encrypted with a key derived from the password; any script on this origin + can read the ciphertext, so pick a password you would not reuse + carelessly. +

+ +
+ Keyring + + + + + + +
+ +
+ Secret + + + + + + + + +
+ +

Not opened.

+ + + + diff --git a/examples/web/main.js b/examples/web/main.js new file mode 100644 index 0000000..9ce341b --- /dev/null +++ b/examples/web/main.js @@ -0,0 +1,104 @@ +// A browser page that keeps a cryptex keyring in IndexedDB. +// +// Build first: +// wasm-pack build --target web --out-dir examples/web/pkg -- --no-default-features --features js +// Then serve this directory over http (not file://): +// python3 -m http.server -d examples/web 8080 + +import init, { Keyring, requestPersistentStorage } from "./pkg/cryptex.js"; + +const $ = (id) => document.getElementById(id); + +let keyring = null; + +function show(message) { + $("status").textContent = message; +} + +/** Connection strings are `password=... salt=...`. */ +function connection() { + const password = $("password").value; + if (!password) throw new Error("Enter a password first"); + return `password=${password} salt=cryptex-browser-example`; +} + +async function open() { + await init(); + if (keyring) await keyring.close(); + keyring = await Keyring.open(connection(), $("name").value, { + backend: "turso", + store: "indexeddb", + }); + show(`Opened "${$("name").value}".`); +} + +async function guarded(action) { + try { + await action(); + } catch (error) { + show(`${error}`); + } +} + +$("open").addEventListener("click", () => + guarded(async () => { + await open(); + const ids = []; + // Reading a secret that is not there is an error, not an empty value. + for (const id of ["api-token"]) { + try { + keyring.get(id); + ids.push(id); + } catch (error) { + if (!String(error).startsWith("ItemNotFound")) throw error; + } + } + if (ids.length) show(`Opened "${$("name").value}"; it holds ${ids.join(", ")}.`); + }), +); + +$("persist").addEventListener("click", () => + guarded(async () => { + await init(); + const granted = await requestPersistentStorage(); + show( + granted + ? "The browser will not evict this origin's storage under pressure." + : "The browser did not grant persistent storage; it may still evict the keyring.", + ); + }), +); + +$("set").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + await keyring.set($("id").value, new TextEncoder().encode($("value").value)); + show(`Stored "${$("id").value}". It is on disk, encrypted, before this line ran.`); + }), +); + +$("get").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + const bytes = keyring.get($("id").value); + show(`${$("id").value} is ${new TextDecoder().decode(bytes)}`); + }), +); + +$("delete").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + await keyring.delete($("id").value); + show(`Deleted "${$("id").value}".`); + }), +); + +$("export").addEventListener("click", () => + guarded(async () => { + if (!keyring) throw new Error("Open the keyring first"); + const image = keyring.export(); + const text = Array.from(image, (b) => b.toString(16).padStart(2, "0")).join(""); + await navigator.clipboard.writeText(text); + show(`Copied ${image.length} encrypted bytes to the clipboard.`); + }), +); diff --git a/examples/web/worker.js b/examples/web/worker.js new file mode 100644 index 0000000..df54d2f --- /dev/null +++ b/examples/web/worker.js @@ -0,0 +1,64 @@ +// A dedicated worker that keeps a cryptex keyring in the origin private file +// system (OPFS). +// +// OPFS sync access handles only exist in a worker, and deriving the key with +// Argon2 blocks whichever thread it runs on, so this is where the keyring +// belongs. +// +// Build first: +// wasm-pack build --target web --out-dir examples/web/pkg -- --no-default-features --features js +// Then, from the page: +// const worker = new Worker("./worker.js", { type: "module" }); +// worker.postMessage({ id: 1, op: "open", password: "...", name: "example" }); + +import init, { Keyring } from "./pkg/cryptex.js"; + +let ready = null; +let keyring = null; + +async function open({ password, name }) { + ready ??= init(); + await ready; + if (keyring) await keyring.close(); + keyring = await Keyring.open( + `password=${password} salt=cryptex-browser-example`, + name, + { backend: "turso", store: "opfs" }, + ); +} + +self.addEventListener("message", async (event) => { + const { id, op, ...args } = event.data; + try { + switch (op) { + case "open": + await open(args); + postMessage({ id, ok: true }); + break; + case "set": + await keyring.set(args.key, new TextEncoder().encode(args.value)); + postMessage({ id, ok: true }); + break; + case "get": + postMessage({ + id, + ok: true, + value: new TextDecoder().decode(keyring.get(args.key)), + }); + break; + case "delete": + await keyring.delete(args.key); + postMessage({ id, ok: true }); + break; + case "close": + await keyring.close(); + keyring = null; + postMessage({ id, ok: true }); + break; + default: + throw new Error(`unknown operation ${op}`); + } + } catch (error) { + postMessage({ id, ok: false, error: String(error) }); + } +}); diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 664ab0d..03cd0a5 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -191,6 +191,18 @@ impl TursoKeyring { Ok(keyring) } + /// Copy every secret into a new in-memory keyring under `params`. + /// + /// The caller's keyring is left untouched, so a failed rekey changes + /// nothing. This is how a keyring without a file of its own is rekeyed. + pub fn copy_under(&self, params: &ConnectionParams) -> Result { + let io = WebIo::in_memory(); + let mut copy = Self::open_web(Arc::clone(&io), "cryptex.db3", params)?; + copy.web = Some(io); + self.file.copy_into(©.file)?; + Ok(copy) + } + /// Copy the whole in-memory database into one encrypted blob. /// /// Fails for a keyring opened from a path or from a caller's connection: diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index b5090e7..9e66b70 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -249,6 +249,11 @@ impl TursoFile { }) } + /// Copy every secret into another keyring's store. + pub(crate) fn copy_into(&self, dst: &TursoFile) -> Result<()> { + self.store.copy_into(&dst.store) + } + /// Path of the main database file, when cryptex opened it itself. #[cfg(feature = "turso")] pub(crate) fn db_path(&self) -> Option<&Path> { diff --git a/src/keyring/web_storage.rs b/src/keyring/web_storage.rs index c19c696..393c346 100644 --- a/src/keyring/web_storage.rs +++ b/src/keyring/web_storage.rs @@ -43,11 +43,59 @@ pub type ConnectionParams = file_common::ConnectionParams; /// `localStorage` key used when no name is given. pub const DEFAULT_NAME: &str = "cryptex"; +/// The encrypted image of a keyring, kept in one `localStorage` entry. +/// +/// The image is the same blob [`MemoryKeyring::export`] and +/// [`TursoKeyring::export`](crate::turso::TursoKeyring::export) produce, so a +/// Turso keyring can use this store too. +pub struct LocalStorageImage { + entry: String, +} + +impl LocalStorageImage { + /// Name the entry for a keyring called `name` (default [`DEFAULT_NAME`]). + pub fn new(name: Option<&str>) -> Result { + Ok(Self { + entry: entry_name(name), + }) + } + + /// The `localStorage` key this image is stored under. + pub fn entry(&self) -> &str { + &self.entry + } + + /// Read the stored image, if there is one. + pub fn load(&self) -> Result>> { + let storage = storage()?; + match storage.get_item(&self.entry).map_err(js_error)? { + Some(encoded) => hex::decode(encoded).map(Some).map_err(|_| invalid_blob()), + None => Ok(None), + } + } + + /// Write an image, replacing any previous one. + pub fn save(&self, image: &[u8]) -> Result<()> { + storage()? + .set_item(&self.entry, &hex::encode(image)) + .map_err(|e| match js_error(e) { + KeyRingError::GeneralError { msg } => KeyRingError::GeneralError { + msg: format!("unable to store the keyring in localStorage: {msg}"), + }, + other => other, + }) + } + + /// Remove the stored image. + pub fn delete(&self) -> Result<()> { + storage()?.remove_item(&self.entry).map_err(js_error) + } +} + /// A keyring whose image lives in `localStorage`. pub struct WebStorageKeyring { inner: MemoryKeyring, - /// `localStorage` key holding the image. - entry: String, + image: LocalStorageImage, } impl WebStorageKeyring { @@ -57,21 +105,17 @@ impl WebStorageKeyring { /// A stored image is decrypted with the password or key in `params`; a /// wrong one returns [`KeyRingError::AccessDenied`]. pub fn with_params(params: &ConnectionParams, name: Option<&str>) -> Result { - let entry = entry_name(name); - let storage = storage()?; - let inner = match storage.get_item(&entry).map_err(js_error)? { - Some(encoded) => { - let blob = hex::decode(encoded).map_err(|_| invalid_blob())?; - MemoryKeyring::import(&blob, password_or_key(params)) - } + let image = LocalStorageImage::new(name)?; + let inner = match image.load()? { + Some(blob) => MemoryKeyring::import(&blob, password_or_key(params)), None => MemoryKeyring::with_params(params), }?; - Ok(Self { inner, entry }) + Ok(Self { inner, image }) } /// The `localStorage` key this keyring is stored under. pub fn entry(&self) -> &str { - &self.entry + self.image.entry() } /// Copy the encrypted image out, e.g. to move it to another backend. @@ -92,19 +136,11 @@ impl WebStorageKeyring { /// Remove the stored image, leaving this keyring's contents in memory. pub fn forget(&self) -> Result<()> { - storage()?.remove_item(&self.entry).map_err(js_error) + self.image.delete() } fn persist(&self) -> Result<()> { - let image = self.inner.export()?; - storage()? - .set_item(&self.entry, &hex::encode(image)) - .map_err(|e| match js_error(e) { - KeyRingError::GeneralError { msg } => KeyRingError::GeneralError { - msg: format!("unable to store the keyring in localStorage: {msg}"), - }, - other => other, - }) + self.image.save(&self.inner.export()?) } } diff --git a/src/lib.rs b/src/lib.rs index dc28cd1..b3d5997 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -57,6 +57,9 @@ pub use keyring::indexeddb; pub use keyring::memory; #[cfg(feature = "web-storage")] pub use keyring::web_storage; + +#[cfg(feature = "js")] +mod wasm; #[cfg(feature = "file")] #[cfg_attr(docsrs, doc(cfg(feature = "file")))] pub use keyring::sqlcipher; diff --git a/src/wasm.rs b/src/wasm.rs new file mode 100644 index 0000000..8f36249 --- /dev/null +++ b/src/wasm.rs @@ -0,0 +1,416 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! JavaScript bindings, for use from a browser with `wasm-bindgen`. +//! +//! ```js +//! import init, { Keyring } from "./pkg/cryptex.js"; +//! await init(); +//! +//! const keyring = await Keyring.open( +//! "password=mysecret salt=0okm9ijn8uhb7ygv", +//! "settings", +//! { backend: "turso", store: "indexeddb" }, +//! ); +//! await keyring.set("api-token", new TextEncoder().encode("secret")); +//! const token = keyring.get("api-token"); +//! await keyring.close(); +//! ``` +//! +//! Backends: +//! +//! | `backend` | what it is | +//! | --- | --- | +//! | `turso` (default) | a Turso database, encrypted with the key from the connection string | +//! | `memory` | an encrypted image in memory, no database | +//! +//! Stores, in order of preference: +//! +//! | `store` | where the image lives | works in | +//! | --- | --- | --- | +//! | `indexeddb` (default) | IndexedDB, one image per keyring, guarded by a Web Lock | page and worker | +//! | `localstorage` | `localStorage`, one string per keyring | page only | +//! | `opfs` | origin private file system, one file per keyring | worker only, `backend: "turso"` only | +//! | `memory` | nowhere: the keyring is gone when the page unloads | page and worker | +//! +//! Every store keeps the image encrypted; the key comes from the password (or +//! raw key) in the connection string. What a store protects against is other +//! origins and other users, not scripts running on the same origin: any script +//! there can read IndexedDB, OPFS and `localStorage`. +//! +//! Deriving the key runs Argon2, which blocks the thread it runs on. Open the +//! keyring in a worker (or with default parameters) to keep the page +//! responsive. + +use js_sys::Reflect; +use wasm_bindgen::prelude::*; +use zeroize::Zeroizing; + +use crate::error::KeyRingError; +use crate::indexeddb::SnapshotStore; +use crate::memory::MemoryKeyring; +use crate::turso::TursoKeyring; +use crate::web_storage::{self, LocalStorageImage, WebStorageKeyring}; +use crate::DynKeyRing; + +/// A keyring, opened from JavaScript. +#[wasm_bindgen] +pub struct Keyring { + inner: Inner, +} + +enum Inner { + /// A Turso keyring plus the store its image is written to. + Turso { + keyring: TursoKeyring, + store: Store, + dirty: bool, + }, + Memory(MemoryKeyring), + WebStorage(WebStorageKeyring), +} + +enum Store { + /// The keyring persists itself, or is not persisted at all. + None, + /// The database is an OPFS file; it holds its own data. + Opfs, + IndexedDb(SnapshotStore), + LocalStorage(LocalStorageImage), +} + +#[wasm_bindgen] +impl Keyring { + /// Open the keyring called `name`, creating it on first use. + /// + /// `connection` is a connection string such as + /// `password=mysecret salt=0okm9ijn8uhb7ygv`. `options` may name a + /// `backend` and a `store`; both default as shown above. A stored keyring + /// is refused with an `AccessDenied` error when the key is wrong. + #[wasm_bindgen(js_name = "open")] + pub async fn open(connection: &str, name: &str, options: JsValue) -> Result { + let options = Options::parse(options)?; + let name = if name.is_empty() { "default" } else { name }; + match options.backend { + Backend::Turso => open_turso(connection, name, options.store).await, + Backend::Memory => open_memory(connection, name, options.store), + } + } + + /// Reopen a keyring from an image returned by [`export`](Self::export). + /// + /// Only `backend` is consulted: the image is used as given, so nothing is + /// read from storage and nothing is written until the first change. + #[wasm_bindgen(js_name = "import")] + pub async fn import( + connection: &str, + image: &[u8], + options: JsValue, + ) -> Result { + let options = Options::parse(options)?; + match options.backend { + Backend::Turso => { + let keyring = TursoKeyring::from_bytes(image, &turso_params(connection)?) + .map_err(js)?; + Ok(Keyring { + inner: Inner::Turso { + keyring, + store: Store::None, + dirty: false, + }, + }) + } + Backend::Memory => { + let keyring = + MemoryKeyring::import(image, &memory_secret(connection)?).map_err(js)?; + Ok(Keyring { + inner: Inner::Memory(keyring), + }) + } + } + } + + /// Read a secret. Throws `ItemNotFound` when there is none. + pub fn get(&mut self, id: &str) -> Result, JsError> { + let secret = match &mut self.inner { + Inner::Turso { keyring, .. } => keyring.get_secret(id), + Inner::Memory(keyring) => keyring.get_secret(id), + Inner::WebStorage(keyring) => keyring.get_secret(id), + } + .map_err(js)?; + let value: Zeroizing> = Zeroizing::new(secret.0.clone()); + Ok(value.to_vec()) + } + + /// Store a secret, replacing any previous value. + /// + /// Resolves once the change has reached storage, so a resolved promise + /// means the secret survives a reload. + pub async fn set(&mut self, id: &str, secret: &[u8]) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + keyring.set_secret(id, secret).map_err(js)?; + *dirty = true; + flush(keyring, store, dirty).await + } + Inner::Memory(keyring) => keyring.set_secret(id, secret).map_err(js), + Inner::WebStorage(keyring) => keyring.set_secret(id, secret).map_err(js), + } + } + + /// Remove a secret. Resolves once storage has been updated. + pub async fn delete(&mut self, id: &str) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + keyring.delete_secret(id).map_err(js)?; + *dirty = true; + flush(keyring, store, dirty).await + } + Inner::Memory(keyring) => keyring.delete_secret(id).map_err(js), + Inner::WebStorage(keyring) => keyring.delete_secret(id).map_err(js), + } + } + + /// Re-encrypt under a new connection string and store the result. + /// + /// Nothing changes if the new key cannot be applied. An OPFS keyring + /// cannot be rekeyed in place: create a keyring with a new name and copy + /// the secrets into it. + pub async fn rekey(&mut self, connection: &str) -> Result<(), JsError> { + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + if matches!(store, Store::Opfs) { + return Err(JsError::new( + "GeneralError: an OPFS keyring cannot be rekeyed in place; \ + open a keyring with a new name and copy the secrets into it", + )); + } + let params = turso_params(connection)?; + // Build the replacement first: if it fails, the keyring the + // caller holds is untouched. + let rekeyed = keyring.copy_under(¶ms).map_err(js)?; + *keyring = rekeyed; + *dirty = true; + flush(keyring, store, dirty).await + } + Inner::Memory(keyring) => keyring.rekey(&memory_params(connection)?).map_err(js), + Inner::WebStorage(keyring) => keyring.rekey(&memory_params(connection)?).map_err(js), + } + } + + /// Copy the encrypted image out, e.g. to move it to another store. + pub fn export(&self) -> Result, JsError> { + match &self.inner { + Inner::Turso { keyring, .. } => keyring.export().map_err(js), + Inner::Memory(keyring) => keyring.export().map_err(js), + Inner::WebStorage(keyring) => keyring.export().map_err(js), + } + } + + /// Flush any pending change and release the store. + /// + /// A keyring holding a Web Lock releases it here, letting another tab + /// open the same name. The keyring still answers reads and writes, but it + /// no longer has anywhere to persist them. + pub async fn close(&mut self) -> Result<(), JsError> { + if let Inner::Turso { + keyring, + store, + dirty, + } = &mut self.inner + { + flush(keyring, store, dirty).await?; + *store = Store::None; + } + Ok(()) + } +} + +/// Ask the browser not to evict this origin's storage. +/// +/// Browsers may grant it silently, prompt, or refuse. Call it while the user +/// is interacting with the page; without it a browser under storage pressure +/// can delete the keyring. +#[wasm_bindgen(js_name = "requestPersistentStorage")] +pub async fn request_persistent_storage() -> Result { + web_storage::request_persistent_storage().await.map_err(js) +} + +async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result { + let params = turso_params(connection)?; + let (keyring, store) = match store { + StoreKind::IndexedDb => { + let snapshot = SnapshotStore::open(name).await.map_err(js)?; + let keyring = match snapshot.load().await.map_err(js)? { + Some(image) => TursoKeyring::from_bytes(&image, ¶ms).map_err(js)?, + None => TursoKeyring::in_memory(¶ms).map_err(js)?, + }; + (keyring, Store::IndexedDb(snapshot)) + } + StoreKind::LocalStorage => { + let image = LocalStorageImage::new(Some(name))?; + let keyring = match image.load()? { + Some(bytes) => TursoKeyring::from_bytes(&bytes, ¶ms).map_err(js)?, + None => TursoKeyring::in_memory(¶ms).map_err(js)?, + }; + (keyring, Store::LocalStorage(image)) + } + StoreKind::Opfs => { + let keyring = TursoKeyring::open_opfs(¶ms, name).await.map_err(js)?; + (keyring, Store::Opfs) + } + StoreKind::Memory => (TursoKeyring::in_memory(¶ms).map_err(js)?, Store::None), + }; + Ok(Keyring { + inner: Inner::Turso { + keyring, + store, + dirty: false, + }, + }) +} + +fn open_memory(connection: &str, name: &str, store: StoreKind) -> Result { + match store { + StoreKind::LocalStorage => { + let keyring = + WebStorageKeyring::with_params(&memory_params(connection)?, Some(name)).map_err(js)?; + Ok(Keyring { + inner: Inner::WebStorage(keyring), + }) + } + StoreKind::IndexedDb | StoreKind::Opfs | StoreKind::Memory => { + let keyring = MemoryKeyring::with_params(&memory_params(connection)?).map_err(js)?; + Ok(Keyring { + inner: Inner::Memory(keyring), + }) + } + } +} + +async fn flush(keyring: &TursoKeyring, store: &Store, dirty: &mut bool) -> Result<(), JsError> { + if !*dirty { + return Ok(()); + } + let image = keyring.export().map_err(js)?; + match store { + Store::None | Store::Opfs => {} + Store::IndexedDb(snapshot) => snapshot.save(&image).await.map_err(js)?, + Store::LocalStorage(local) => local.save(&image)?, + } + *dirty = false; + Ok(()) +} + +#[derive(Clone, Copy)] +enum Backend { + Turso, + Memory, +} + +#[derive(Clone, Copy)] +enum StoreKind { + IndexedDb, + LocalStorage, + Opfs, + Memory, +} + +struct Options { + backend: Backend, + store: StoreKind, +} + +impl Options { + fn parse(options: JsValue) -> Result { + let mut parsed = Self { + backend: Backend::Turso, + store: StoreKind::IndexedDb, + }; + if options.is_undefined() || options.is_null() { + return Ok(parsed); + } + if let Some(backend) = string_property(&options, "backend")? { + parsed.backend = match backend.as_str() { + "turso" => Backend::Turso, + "memory" => Backend::Memory, + other => return Err(unknown("backend", other)), + }; + } + if let Some(store) = string_property(&options, "store")? { + parsed.store = match store.as_str() { + "indexeddb" => StoreKind::IndexedDb, + "localstorage" => StoreKind::LocalStorage, + "opfs" => StoreKind::Opfs, + "memory" => StoreKind::Memory, + other => return Err(unknown("store", other)), + }; + } + // OPFS holds database files, so it needs a database backend. + if matches!(parsed.store, StoreKind::Opfs) && matches!(parsed.backend, Backend::Memory) { + return Err(JsError::new( + "TypeError: the opfs store needs backend: \"turso\"", + )); + } + Ok(parsed) + } +} + +fn string_property(value: &JsValue, name: &str) -> Result, JsError> { + let property = Reflect::get(value, &JsValue::from_str(name)) + .map_err(|e| js(KeyRingError::from(e)))?; + if property.is_undefined() || property.is_null() { + return Ok(None); + } + property + .as_string() + .map(Some) + .ok_or_else(|| JsError::new(&format!("TypeError: options.{name} must be a string"))) +} + +fn unknown(field: &str, value: &str) -> JsError { + JsError::new(&format!( + "TypeError: unknown {field} '{value}'; expected one of the documented values" + )) +} + +fn turso_params(connection: &str) -> Result { + connection.parse().map_err(js) +} + +fn memory_params(connection: &str) -> Result { + connection.parse().map_err(js) +} + +/// The password or raw key from a connection string, for a memory keyring. +fn memory_secret(connection: &str) -> Result, JsError> { + let params = memory_params(connection)?; + Ok(if params.key.is_empty() { + params.password.clone() + } else { + params.key.clone() + }) +} + +fn js(error: KeyRingError) -> JsError { + // Keep the kind as the first word so JavaScript can switch on it. + let kind = match &error { + KeyRingError::ItemNotFound => "ItemNotFound", + KeyRingError::AccessDenied { .. } => "AccessDenied", + KeyRingError::GeneralError { .. } => "GeneralError", + }; + JsError::new(&format!("{kind}: {error}")) +} From 5dd9f73396a300d3eb928044fc99026b3156a028 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 14:57:03 -0500 Subject: [PATCH 06/18] Keep a browser keyring reopenable: unique database paths and a real close An in-memory keyring opened its database under one fixed path, so two of them shared a page cache and an encryption key. Give each its own path, reopen an imported image under the path it was written as, and let a rekey copy into a fresh database instead of replacing the one in place. Closing a JavaScript keyring now drops the underlying database, which is what releases an OPFS sync access handle or an IndexedDB lock, and the flush no longer tries to export an OPFS keyring that has no image. --- src/keyring/indexeddb.rs | 3 ++- src/keyring/turso.rs | 35 +++++++++++++++++++++++++++++++---- src/keyring/turso_web.rs | 20 ++++++++++++++++++++ src/wasm.rs | 38 +++++++++++++++++++++++++++++--------- 4 files changed, 82 insertions(+), 14 deletions(-) diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs index bbf62ac..bfffa31 100644 --- a/src/keyring/indexeddb.rs +++ b/src/keyring/indexeddb.rs @@ -209,7 +209,8 @@ impl Drop for LockHold { } async fn open_db() -> Result { - let factory: IdbFactory = Reflect::get(&navigator()?, &JsValue::from_str("indexedDB")) + // `indexedDB` hangs off the global object, not off `navigator`. + let factory: IdbFactory = Reflect::get(&js_sys::global(), &JsValue::from_str("indexedDB")) .map_err(js_error)? .dyn_into() .map_err(|_| unsupported("this browser has no IndexedDB"))?; diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 03cd0a5..305da43 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -18,7 +18,7 @@ use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_ use super::turso_common::TursoFile; #[cfg(feature = "opfs")] use super::opfs::OpfsIo; -use super::turso_web::WebIo; +use super::turso_web::{WebIo, unique_db_path}; use crate::error::KeyRingError; /// The cipher Turso uses to encrypt database pages. @@ -161,13 +161,19 @@ impl TursoKeyring { /// with [`from_bytes`](Self::from_bytes). pub fn in_memory(params: &ConnectionParams) -> Result { let io = WebIo::in_memory(); - Self::open_web(Arc::clone(&io), "cryptex.db3", params).map(|k| Self { web: Some(io), ..k }) + let path = unique_db_path(); + Self::open_web(Arc::clone(&io), &path, params).map(|k| Self { web: Some(io), ..k }) } /// Reopen a keyring from an image produced by [`export`](Self::export). pub fn from_bytes(bytes: &[u8], params: &ConnectionParams) -> Result { let io = WebIo::restore(bytes)?; - Self::open_web(Arc::clone(&io), "cryptex.db3", params).map(|k| Self { web: Some(io), ..k }) + // The image remembers the path it was written under; Turso keys open + // databases by path, so it has to be opened as that path. + let path = io.db_path().ok_or_else(|| KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring image".to_string(), + })?; + Self::open_web(Arc::clone(&io), &path, params).map(|k| Self { web: Some(io), ..k }) } fn open_web(io: Arc, path: &str, params: &ConnectionParams) -> Result { @@ -197,7 +203,8 @@ impl TursoKeyring { /// nothing. This is how a keyring without a file of its own is rekeyed. pub fn copy_under(&self, params: &ConnectionParams) -> Result { let io = WebIo::in_memory(); - let mut copy = Self::open_web(Arc::clone(&io), "cryptex.db3", params)?; + let path = unique_db_path(); + let mut copy = Self::open_web(Arc::clone(&io), &path, params)?; copy.web = Some(io); self.file.copy_into(©.file)?; Ok(copy) @@ -322,6 +329,26 @@ mod tests { assert!(TursoKeyring::from_bytes(b"not a snapshot", &p).is_err()); } + #[test] + fn copy_under_rekeys_without_touching_the_original() { + let a = params("password=first salt=1qaz2wsx3edc4rfv5tgb"); + let b = params("password=second salt=1qaz2wsx3edc4rfv5tgb"); + let wrong = params("password=third salt=1qaz2wsx3edc4rfv5tgb"); + + let mut original = TursoKeyring::in_memory(&a).unwrap(); + original.set_secret("k1", b"value1").unwrap(); + + let copy = original.copy_under(&b).unwrap(); + let image = copy.export().unwrap(); + + let mut reopened = TursoKeyring::from_bytes(&image, &b).unwrap(); + assert_eq!(reopened.get_secret("k1").unwrap().0, b"value1"); + assert!(TursoKeyring::from_bytes(&image, &wrong).is_err()); + + // The original still opens with its own key. + assert_eq!(original.get_secret("k1").unwrap().0, b"value1"); + } + #[test] fn export_needs_an_in_memory_keyring() { let dir = TestDir::new(".test-turso-export"); diff --git a/src/keyring/turso_web.rs b/src/keyring/turso_web.rs index 92c977a..ebe5157 100644 --- a/src/keyring/turso_web.rs +++ b/src/keyring/turso_web.rs @@ -47,6 +47,15 @@ impl WebIo { }) } + /// The path of the database file in this IO, if it has one. + pub(crate) fn db_path(&self) -> Option { + let files = self.files.lock().ok()?; + files + .keys() + .find(|path| path.ends_with(".db3")) + .cloned() + } + /// Copy every file into one blob. /// /// Layout: `magic (10) | version (1) | count (u32 LE)` then, per file in @@ -120,6 +129,17 @@ impl WebIo { } } +/// A database path no other in-memory keyring uses. +/// +/// Turso keys its open databases by path, so two in-memory keyrings that +/// shared one would share a page cache and an encryption key. +pub(crate) fn unique_db_path() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(1); + format!("cryptex-{}.db3", NEXT.fetch_add(1, Ordering::Relaxed)) +} + fn poisoned() -> KeyRingError { KeyRingError::GeneralError { msg: "the in-memory database lock is poisoned".to_string(), diff --git a/src/wasm.rs b/src/wasm.rs index 8f36249..6577eaf 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -63,7 +63,9 @@ pub struct Keyring { enum Inner { /// A Turso keyring plus the store its image is written to. Turso { - keyring: TursoKeyring, + /// `None` once the keyring is closed: dropping it releases the + /// database, and with it an OPFS handle or an IndexedDB lock. + keyring: Option, store: Store, dirty: bool, }, @@ -115,7 +117,7 @@ impl Keyring { .map_err(js)?; Ok(Keyring { inner: Inner::Turso { - keyring, + keyring: Some(keyring), store: Store::None, dirty: false, }, @@ -134,7 +136,9 @@ impl Keyring { /// Read a secret. Throws `ItemNotFound` when there is none. pub fn get(&mut self, id: &str) -> Result, JsError> { let secret = match &mut self.inner { - Inner::Turso { keyring, .. } => keyring.get_secret(id), + Inner::Turso { keyring, .. } => { + keyring.as_mut().ok_or_else(closed)?.get_secret(id) + } Inner::Memory(keyring) => keyring.get_secret(id), Inner::WebStorage(keyring) => keyring.get_secret(id), } @@ -154,6 +158,7 @@ impl Keyring { store, dirty, } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.set_secret(id, secret).map_err(js)?; *dirty = true; flush(keyring, store, dirty).await @@ -171,6 +176,7 @@ impl Keyring { store, dirty, } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.delete_secret(id).map_err(js)?; *dirty = true; flush(keyring, store, dirty).await @@ -199,6 +205,7 @@ impl Keyring { )); } let params = turso_params(connection)?; + let keyring = keyring.as_mut().ok_or_else(closed)?; // Build the replacement first: if it fails, the keyring the // caller holds is untouched. let rekeyed = keyring.copy_under(¶ms).map_err(js)?; @@ -214,7 +221,9 @@ impl Keyring { /// Copy the encrypted image out, e.g. to move it to another store. pub fn export(&self) -> Result, JsError> { match &self.inner { - Inner::Turso { keyring, .. } => keyring.export().map_err(js), + Inner::Turso { keyring, .. } => { + keyring.as_ref().ok_or_else(closed)?.export().map_err(js) + } Inner::Memory(keyring) => keyring.export().map_err(js), Inner::WebStorage(keyring) => keyring.export().map_err(js), } @@ -232,7 +241,10 @@ impl Keyring { dirty, } = &mut self.inner { - flush(keyring, store, dirty).await?; + if let Some(keyring) = keyring.as_ref() { + flush(keyring, store, dirty).await?; + } + *keyring = None; *store = Store::None; } Ok(()) @@ -276,7 +288,7 @@ async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result Resul if !*dirty { return Ok(()); } - let image = keyring.export().map_err(js)?; match store { + // OPFS holds the database file itself: Turso's own writes are the + // persistence, so there is no image to copy out. Store::None | Store::Opfs => {} - Store::IndexedDb(snapshot) => snapshot.save(&image).await.map_err(js)?, - Store::LocalStorage(local) => local.save(&image)?, + Store::IndexedDb(snapshot) => snapshot + .save(&keyring.export().map_err(js)?) + .await + .map_err(js)?, + Store::LocalStorage(local) => local.save(&keyring.export().map_err(js)?)?, } *dirty = false; Ok(()) @@ -405,6 +421,10 @@ fn memory_secret(connection: &str) -> Result, JsError> { }) } +fn closed() -> JsError { + JsError::new("GeneralError: the keyring is closed") +} + fn js(error: KeyRingError) -> JsError { // Keep the kind as the first word so JavaScript can switch on it. let kind = match &error { From ed01c4ed0180441a55f4f29afdcd53891616cdbe Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 15:07:35 -0500 Subject: [PATCH 07/18] Store memory keyrings in IndexedDB and wait for a lock to be released The memory backend writes its sealed image to IndexedDB too, so the only difference from the default is that there is no database underneath. That also makes the localStorage path the same code, and asking for OPFS with a memory keyring is refused instead of silently losing the store. Closing a keyring now waits for the Web Lock to actually be released: the release is asynchronous, so reopening the same name in the same page could otherwise be refused. Browser tests for the bindings join the repository as tests/wasm.rs, run with . --- Cargo.toml | 8 +- README.md | 73 +++++++++++++++- src/keyring/indexeddb.rs | 27 +++++- src/keyring/turso_common.rs | 16 ++-- src/keyring/web_time.rs | 12 +-- src/lib.rs | 3 + src/wasm.rs | 165 +++++++++++++++++++++++++----------- tests/wasm.rs | 80 +++++++++++++++++ 8 files changed, 314 insertions(+), 70 deletions(-) create mode 100644 tests/wasm.rs diff --git a/Cargo.toml b/Cargo.toml index 6ed8d1e..265e7be 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,13 @@ web-storage = [ "dep:js-sys", ] indexeddb = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] -opfs = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] +opfs = [ + "turso", + "dep:web-sys", + "dep:wasm-bindgen", + "dep:wasm-bindgen-futures", + "dep:js-sys", +] js = [ "memory", "web-storage", diff --git a/README.md b/README.md index 0b71729..b940f92 100644 --- a/README.md +++ b/README.md @@ -135,8 +135,12 @@ open. `rekey` re-derives the key without touching the secrets. | Feature | `wasm32-unknown-unknown` | WASI | Notes | |---------|--------------------------|------|-------| | `memory` | yes | yes | encrypted in RAM, export/import | -| `turso` | yes | yes | Turso's native page encryption | -| `turso-encrypted-io` | yes | yes | page cipher in a custom IO | +| `turso` | yes | yes | Turso's native page encryption, including in-memory and OPFS keyrings | +| `turso-encrypted-io` | builds | yes | the page cipher needs a `PageStore`; the file-backed one is native only | +| `web-storage` | yes | no | a `MemoryKeyring` sealed into `localStorage` | +| `indexeddb` | yes | no | encrypted image snapshots, one per keyring | +| `opfs` | yes | no | the database file itself in the origin private file system | +| `js` | yes | no | the `wasm-bindgen` `Keyring` class | | `file`, `encrypted-vfs` | no | no | SQLCipher and the bundled C VFS are native only | | OS keyrings, `yubihsm-*` | no | no | no OS keychain or USB device | @@ -152,6 +156,71 @@ RUSTFLAGS='--cfg getrandom_backend="wasm_js"' \ cargo check --target wasm32-unknown-unknown --no-default-features --features turso ``` +### Browser keyrings + +The `js` feature wraps the backends in a `Keyring` class for JavaScript: + +```bash +wasm-pack build --target web --no-default-features --features js +``` + +```js +import init, { Keyring, requestPersistentStorage } from "./pkg/cryptex.js"; + +await init(); + +// An encrypted Turso database, persisted in IndexedDB. These are the defaults. +const keyring = await Keyring.open("password=hunter2 salt=0okm9ijn8uhb7ygv", "settings"); +await keyring.set("api-token", new TextEncoder().encode("s3cret")); +const token = keyring.get("api-token"); // Uint8Array +await keyring.delete("api-token"); + +// Ask the browser not to evict the origin's storage. +await requestPersistentStorage(); +await keyring.close(); +``` + +`open(connection, name, options)` chooses where the keyring lives: + +| `backend` | `store` | What is persisted | +|-----------|---------|-------------------| +| `"turso"` (default) | `"indexeddb"` (default) | the encrypted database image, saved after every change | +| `"turso"` | `"opfs"` | the database file itself, in the origin private file system | +| `"turso"` | `"memory"` | nothing; `export()` the image yourself | +| `"memory"` | `"localstorage"` | a sealed blob under `localStorage["cryptex:"]` | +| `"memory"` | `"memory"` | nothing | + +`import(connection, image, options)` reopens an image returned by `export()`, +and `rekey(connection)` changes its password. + +Every store keeps the data encrypted; the key comes from the password (or raw +key) in the connection string, so a store with the wrong connection string +fails with `AccessDenied` instead of returning garbage. + +A `set` or `delete` that resolves has reached the store. An IndexedDB keyring +also holds a Web Lock named after itself, so a second tab that opens the same +name fails with `AccessDenied` instead of overwriting the first tab's secrets; +`close()` releases the lock, and with OPFS the sync access handle, so close a +keyring before opening it again in the same context. + +OPFS needs `createSyncAccessHandle()`, which browsers expose only in a +dedicated worker, so `store: "opfs"` is refused on the main thread. A worker +can use IndexedDB too. `examples/web/` has a page that uses IndexedDB and a +worker that uses OPFS; serve it over HTTP (`python3 -m http.server`), because +wasm modules and OPFS are not available on `file://` URLs. + +Errors are `Error` objects whose message starts with the kind, so a caller can +switch on `ItemNotFound:`, `AccessDenied:`, `TypeError:` or `GeneralError:` +without parsing the rest. + +Two costs are worth planning for. Any script the origin loads can read +IndexedDB, OPFS and `localStorage`, so the encryption protects against other +origins and other users, not against a compromised page. +`requestPersistentStorage()` asks the browser to keep the data, but it may +refuse, and clearing site data always removes it. Key derivation runs Argon2, +which blocks the thread it runs on: with a large `memory=` value, open the +keyring in a worker or the page freezes until it finishes. + ### Bringing your own storage `TursoKeyring` can adopt a connection you opened, or open through an IO you diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs index bfffa31..2a211da 100644 --- a/src/keyring/indexeddb.rs +++ b/src/keyring/indexeddb.rs @@ -48,7 +48,7 @@ const STORE_NAME: &str = "keyrings"; pub struct SnapshotStore { name: String, db: IdbDatabase, - _hold: LockHold, + hold: LockHold, } impl SnapshotStore { @@ -59,7 +59,7 @@ impl SnapshotStore { Ok(Self { name: name.to_string(), db, - _hold: hold, + hold, }) } @@ -68,6 +68,14 @@ impl SnapshotStore { &self.name } + /// Release the lock and wait until the browser has done so. + /// + /// Releasing is asynchronous: without this wait, opening the same name + /// again in the same page can still see the old lock and be refused. + pub async fn release(&mut self) { + self.hold.release_async().await; + } + /// Read the stored image, if there is one. pub async fn load(&self) -> Result>> { let tx = self.transaction(IdbTransactionMode::Readonly)?; @@ -114,6 +122,8 @@ struct LockHold { release: std::rc::Rc>>, /// The promise itself: the lock is held until it settles. _held: js_sys::Promise, + /// Resolves once the lock has been released. + released: js_sys::Promise, /// The callback, kept alive because the browser may still call it. _callback: JsValue, } @@ -195,11 +205,24 @@ impl LockHold { Ok(Self { release, _held: held, + released: request_promise, _callback: callback, }) } } +impl LockHold { + /// Release the lock and wait for the browser to finish doing so. + async fn release_async(&mut self) { + if let Some(release) = self.release.borrow_mut().take() { + let _ = release.call0(&JsValue::NULL); + } + // The request settles only after the lock is gone, so awaiting it is + // what makes an immediate reopen of the same name work. + let _ = JsFuture::from(self.released.clone()).await; + } +} + impl Drop for LockHold { fn drop(&mut self) { if let Some(release) = self.release.borrow_mut().take() { diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index 9e66b70..83e27e6 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -14,8 +14,11 @@ use std::fs::File; use std::future::Future; use std::path::{Path, PathBuf}; use std::pin::pin; +#[cfg(not(target_family = "wasm"))] use std::sync::Arc; -use std::task::{Context, Poll, Wake, Waker}; +#[cfg(not(target_family = "wasm"))] +use std::task::Wake; +use std::task::{Context, Poll, Waker}; #[cfg(not(target_family = "wasm"))] use std::thread::{self, Thread}; @@ -68,14 +71,6 @@ where #[cfg(target_family = "wasm")] const MAX_WASM_POLLS: usize = 1_000_000; -#[cfg(target_family = "wasm")] -struct SpinWaker; - -#[cfg(target_family = "wasm")] -impl Wake for SpinWaker { - fn wake(self: Arc) {} -} - #[cfg(target_family = "wasm")] pub(crate) fn block_on(fut: F) -> Result where @@ -83,8 +78,7 @@ where E: Into, { let mut fut = pin!(fut); - let waker = Waker::from(Arc::new(SpinWaker)); - let mut cx = Context::from_waker(&waker); + let mut cx = Context::from_waker(Waker::noop()); for _ in 0..MAX_WASM_POLLS { if let Poll::Ready(out) = fut.as_mut().poll(&mut cx) { return out.map_err(Into::into); diff --git a/src/keyring/web_time.rs b/src/keyring/web_time.rs index 793d227..ccff761 100644 --- a/src/keyring/web_time.rs +++ b/src/keyring/web_time.rs @@ -7,7 +7,7 @@ //! Turso's own clock calls `Instant::now`, which panics on //! `wasm32-unknown-unknown`: the platform has no monotonic clock behind it. //! `performance.now()` is the closest equivalent and, unlike `Date.now()`, -//! only moves forward. +//! only moves forward. WASI builds have `std::time` and use it. use ::turso::core::{Clock, MonotonicInstant, WallClockInstant}; @@ -27,7 +27,7 @@ impl Clock for WebClock { /// Milliseconds since the time origin, from `performance.now()`. /// /// A worker has no `window`, so the value is read off the global object. -#[cfg(target_family = "wasm")] +#[cfg(all(target_family = "wasm", target_os = "unknown"))] fn performance_millis() -> Option { use wasm_bindgen::{JsCast, JsValue}; @@ -38,14 +38,14 @@ fn performance_millis() -> Option { now.call0(&performance).ok()?.as_f64() } -#[cfg(target_family = "wasm")] +#[cfg(all(target_family = "wasm", target_os = "unknown"))] fn monotonic_nanos() -> u128 { // Fall back to the wall clock where `performance` is missing. let millis = performance_millis().unwrap_or_else(js_sys::Date::now); (millis * 1_000_000.0) as u128 } -#[cfg(not(target_family = "wasm"))] +#[cfg(not(all(target_family = "wasm", target_os = "unknown")))] fn monotonic_nanos() -> u128 { use std::sync::OnceLock; use std::time::Instant; @@ -54,7 +54,7 @@ fn monotonic_nanos() -> u128 { EPOCH.get_or_init(Instant::now).elapsed().as_nanos() } -#[cfg(target_family = "wasm")] +#[cfg(all(target_family = "wasm", target_os = "unknown"))] fn wall_clock_now() -> WallClockInstant { let millis = js_sys::Date::now(); let secs = (millis / 1000.0).floor(); @@ -65,7 +65,7 @@ fn wall_clock_now() -> WallClockInstant { } } -#[cfg(not(target_family = "wasm"))] +#[cfg(not(all(target_family = "wasm", target_os = "unknown")))] fn wall_clock_now() -> WallClockInstant { use std::time::{SystemTime, UNIX_EPOCH}; diff --git a/src/lib.rs b/src/lib.rs index b3d5997..9e08558 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -60,6 +60,9 @@ pub use keyring::web_storage; #[cfg(feature = "js")] mod wasm; +#[cfg(feature = "js")] +#[cfg_attr(docsrs, doc(cfg(feature = "js")))] +pub use wasm::{Keyring, request_persistent_storage}; #[cfg(feature = "file")] #[cfg_attr(docsrs, doc(cfg(feature = "file")))] pub use keyring::sqlcipher; diff --git a/src/wasm.rs b/src/wasm.rs index 6577eaf..f52e0b9 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -51,7 +51,7 @@ use crate::error::KeyRingError; use crate::indexeddb::SnapshotStore; use crate::memory::MemoryKeyring; use crate::turso::TursoKeyring; -use crate::web_storage::{self, LocalStorageImage, WebStorageKeyring}; +use crate::web_storage::{self, LocalStorageImage}; use crate::DynKeyRing; /// A keyring, opened from JavaScript. @@ -69,8 +69,11 @@ enum Inner { store: Store, dirty: bool, }, - Memory(MemoryKeyring), - WebStorage(WebStorageKeyring), + Memory { + keyring: MemoryKeyring, + store: Store, + dirty: bool, + }, } enum Store { @@ -96,7 +99,7 @@ impl Keyring { let name = if name.is_empty() { "default" } else { name }; match options.backend { Backend::Turso => open_turso(connection, name, options.store).await, - Backend::Memory => open_memory(connection, name, options.store), + Backend::Memory => open_memory(connection, name, options.store).await, } } @@ -127,7 +130,11 @@ impl Keyring { let keyring = MemoryKeyring::import(image, &memory_secret(connection)?).map_err(js)?; Ok(Keyring { - inner: Inner::Memory(keyring), + inner: Inner::Memory { + keyring, + store: Store::None, + dirty: false, + }, }) } } @@ -139,8 +146,7 @@ impl Keyring { Inner::Turso { keyring, .. } => { keyring.as_mut().ok_or_else(closed)?.get_secret(id) } - Inner::Memory(keyring) => keyring.get_secret(id), - Inner::WebStorage(keyring) => keyring.get_secret(id), + Inner::Memory { keyring, .. } => keyring.get_secret(id), } .map_err(js)?; let value: Zeroizing> = Zeroizing::new(secret.0.clone()); @@ -161,10 +167,18 @@ impl Keyring { let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.set_secret(id, secret).map_err(js)?; *dirty = true; - flush(keyring, store, dirty).await + flush(store, dirty, || keyring.export()).await + } + Inner::Memory { + keyring, + store, + dirty, + } => { + keyring.set_secret(id, secret).map_err(js)?; + *dirty = true; + let keyring = &*keyring; + flush(store, dirty, || keyring.export()).await } - Inner::Memory(keyring) => keyring.set_secret(id, secret).map_err(js), - Inner::WebStorage(keyring) => keyring.set_secret(id, secret).map_err(js), } } @@ -179,10 +193,18 @@ impl Keyring { let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.delete_secret(id).map_err(js)?; *dirty = true; - flush(keyring, store, dirty).await + flush(store, dirty, || keyring.export()).await + } + Inner::Memory { + keyring, + store, + dirty, + } => { + keyring.delete_secret(id).map_err(js)?; + *dirty = true; + let keyring = &*keyring; + flush(store, dirty, || keyring.export()).await } - Inner::Memory(keyring) => keyring.delete_secret(id).map_err(js), - Inner::WebStorage(keyring) => keyring.delete_secret(id).map_err(js), } } @@ -211,10 +233,18 @@ impl Keyring { let rekeyed = keyring.copy_under(¶ms).map_err(js)?; *keyring = rekeyed; *dirty = true; - flush(keyring, store, dirty).await + flush(store, dirty, || keyring.export()).await + } + Inner::Memory { + keyring, + store, + dirty, + } => { + keyring.rekey(&memory_params(connection)?).map_err(js)?; + *dirty = true; + let keyring = &*keyring; + flush(store, dirty, || keyring.export()).await } - Inner::Memory(keyring) => keyring.rekey(&memory_params(connection)?).map_err(js), - Inner::WebStorage(keyring) => keyring.rekey(&memory_params(connection)?).map_err(js), } } @@ -224,8 +254,7 @@ impl Keyring { Inner::Turso { keyring, .. } => { keyring.as_ref().ok_or_else(closed)?.export().map_err(js) } - Inner::Memory(keyring) => keyring.export().map_err(js), - Inner::WebStorage(keyring) => keyring.export().map_err(js), + Inner::Memory { keyring, .. } => keyring.export().map_err(js), } } @@ -235,17 +264,27 @@ impl Keyring { /// open the same name. The keyring still answers reads and writes, but it /// no longer has anywhere to persist them. pub async fn close(&mut self) -> Result<(), JsError> { - if let Inner::Turso { - keyring, - store, - dirty, - } = &mut self.inner - { - if let Some(keyring) = keyring.as_ref() { - flush(keyring, store, dirty).await?; + match &mut self.inner { + Inner::Turso { + keyring, + store, + dirty, + } => { + if let Some(keyring) = keyring.as_ref() { + flush(store, dirty, || keyring.export()).await?; + } + *keyring = None; + release(store).await; + } + Inner::Memory { + keyring, + store, + dirty, + } => { + // The secrets stay readable; they just have nowhere to go. + flush(store, dirty, || keyring.export()).await?; + release(store).await; } - *keyring = None; - *store = Store::None; } Ok(()) } @@ -295,37 +334,67 @@ async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result Result { - match store { +async fn open_memory(connection: &str, name: &str, store: StoreKind) -> Result { + let params = memory_params(connection)?; + let secret = memory_secret(connection)?; + let (keyring, store) = match store { + StoreKind::IndexedDb => { + let snapshot = SnapshotStore::open(name).await.map_err(js)?; + let keyring = match snapshot.load().await.map_err(js)? { + Some(image) => MemoryKeyring::import(&image, &secret).map_err(js)?, + None => MemoryKeyring::with_params(¶ms).map_err(js)?, + }; + (keyring, Store::IndexedDb(snapshot)) + } StoreKind::LocalStorage => { - let keyring = - WebStorageKeyring::with_params(&memory_params(connection)?, Some(name)).map_err(js)?; - Ok(Keyring { - inner: Inner::WebStorage(keyring), - }) + let image = LocalStorageImage::new(Some(name))?; + let keyring = match image.load()? { + Some(bytes) => MemoryKeyring::import(&bytes, &secret).map_err(js)?, + None => MemoryKeyring::with_params(¶ms).map_err(js)?, + }; + (keyring, Store::LocalStorage(image)) } - StoreKind::IndexedDb | StoreKind::Opfs | StoreKind::Memory => { - let keyring = MemoryKeyring::with_params(&memory_params(connection)?).map_err(js)?; - Ok(Keyring { - inner: Inner::Memory(keyring), - }) + StoreKind::Memory => (MemoryKeyring::with_params(¶ms).map_err(js)?, Store::None), + // Refused when the options are parsed; OPFS stores database files. + StoreKind::Opfs => { + return Err(JsError::new( + "TypeError: the opfs store needs backend: \"turso\"", + )); } + }; + Ok(Keyring { + inner: Inner::Memory { + keyring, + store, + dirty: false, + }, + }) +} + +/// Drop the store, releasing a Web Lock only once the browser has done so. +async fn release(store: &mut Store) { + if let Store::IndexedDb(snapshot) = store { + snapshot.release().await; } + *store = Store::None; } -async fn flush(keyring: &TursoKeyring, store: &Store, dirty: &mut bool) -> Result<(), JsError> { +/// Write the keyring's current image to its store. +/// +/// Nothing to do for a keyring that keeps its own data (OPFS) or has no store: +/// `image` is only called when a store actually needs a copy. +async fn flush( + store: &Store, + dirty: &mut bool, + image: impl FnOnce() -> Result, KeyRingError>, +) -> Result<(), JsError> { if !*dirty { return Ok(()); } match store { - // OPFS holds the database file itself: Turso's own writes are the - // persistence, so there is no image to copy out. Store::None | Store::Opfs => {} - Store::IndexedDb(snapshot) => snapshot - .save(&keyring.export().map_err(js)?) - .await - .map_err(js)?, - Store::LocalStorage(local) => local.save(&keyring.export().map_err(js)?)?, + Store::IndexedDb(snapshot) => snapshot.save(&image().map_err(js)?).await.map_err(js)?, + Store::LocalStorage(local) => local.save(&image().map_err(js)?)?, } *dirty = false; Ok(()) diff --git a/tests/wasm.rs b/tests/wasm.rs new file mode 100644 index 0000000..4c60ea9 --- /dev/null +++ b/tests/wasm.rs @@ -0,0 +1,80 @@ +/* + Copyright Michael Lodder. All Rights Reserved. + SPDX-License-Identifier: Apache-2.0 +*/ +//! Browser tests for the JavaScript bindings. +//! +//! Run with `wasm-pack test --headless --chrome --no-default-features +//! --features js`. Native `cargo test` skips this file. + +#![cfg(all(target_family = "wasm", target_os = "unknown"))] + +use cryptex::Keyring; +use wasm_bindgen_test::wasm_bindgen_test; + +wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); + +const CONNECTION: &str = "password=browser-test salt=0okm9ijn8uhb7ygv"; + +/// A keyring name no other run uses, so a leftover store cannot fool a test. +fn unique_name(prefix: &str) -> String { + use std::sync::atomic::{AtomicU32, Ordering}; + + static NEXT: AtomicU32 = AtomicU32::new(0); + format!("{prefix}-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + +#[wasm_bindgen_test] +async fn memory_keyring_round_trips() { + let mut keyring = Keyring::open(CONNECTION, &unique_name("memory"), Default::default()) + .await + .expect("a memory keyring opens"); + + keyring.set("token", b"secret").await.expect("set succeeds"); + assert_eq!(keyring.get("token").expect("get succeeds"), b"secret"); + keyring.delete("token").await.expect("delete succeeds"); + assert!(keyring.get("token").is_err()); + + keyring.close().await.expect("close succeeds"); +} + +#[wasm_bindgen_test] +async fn indexeddb_keeps_the_secrets() { + let name = unique_name("indexeddb"); + + let mut keyring = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("a keyring opens"); + keyring.set("token", b"value").await.expect("set succeeds"); + // A resolved set has reached the store, so the image is encrypted at rest. + let image = keyring.export().expect("export succeeds"); + assert!(!image.windows(5).any(|w| w == b"value")); + keyring.close().await.expect("close succeeds"); + + let mut reopened = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("the keyring reopens"); + assert_eq!(reopened.get("token").expect("get succeeds"), b"value"); + reopened.close().await.expect("close succeeds"); +} + +#[wasm_bindgen_test] +async fn a_wrong_password_is_refused() { + let name = unique_name("indexeddb"); + let mut keyring = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("a keyring opens"); + keyring.set("token", b"value").await.expect("set succeeds"); + keyring.close().await.expect("close succeeds"); + + let result = Keyring::open( + "password=wrong salt=0okm9ijn8uhb7ygv", + &name, + Default::default(), + ) + .await; + match result { + Err(error) => assert!(format!("{error:?}").contains("AccessDenied")), + Ok(_) => panic!("the wrong password is refused"), + } +} From 409759645076c585e6c1a4411e9e664be495ca4a Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 15:10:58 -0500 Subject: [PATCH 08/18] Document the browser backends and test them in headless Chrome The README gains the JavaScript API, the backend/store combinations, what each store persists, the Web Lock that keeps two tabs from fighting over one keyring, and the costs: any script on the origin can read browser storage, the browser may evict it, and Argon2 blocks the thread it runs on. CI builds the wasm package and runs tests/wasm.rs in headless Chrome, and the version moves to 2.5.0. --- .github/workflows/cryptex.yml | 11 +++++++ Cargo.toml | 2 +- README.md | 1 + src/error.rs | 12 ++------ src/keyring.rs | 8 ++--- src/keyring/indexeddb.rs | 22 +++++++++----- src/keyring/opfs.rs | 55 +++++++++++++++++------------------ src/keyring/page_cipher.rs | 8 ++++- src/keyring/page_store.rs | 7 +++-- src/keyring/turso.rs | 2 +- src/keyring/turso_web.rs | 9 ++---- src/keyring/web_storage.rs | 19 +++++++----- src/lib.rs | 14 ++++----- src/wasm.rs | 19 ++++++------ tests/wasm.rs | 2 +- 15 files changed, 105 insertions(+), 86 deletions(-) diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index c9c7bd5..7ef02a4 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -100,8 +100,19 @@ jobs: cargo clippy --target wasm32-unknown-unknown --no-default-features --features turso -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-encrypted-io" -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features memory -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,opfs,indexeddb,web-storage,js" -- -D warnings cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" + - name: Install wasm-pack + run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + - name: Build the JavaScript package + run: wasm-pack build --target web --no-default-features --features js + - name: Set up Chrome and ChromeDriver + uses: browser-actions/setup-chrome@v1 + with: + install-chromedriver: true + - name: Run the browser tests + run: wasm-pack test --headless --chrome --no-default-features --features js --test wasm rustfmt-linux: runs-on: ubuntu-latest diff --git a/Cargo.toml b/Cargo.toml index 265e7be..28c3697 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ keywords = ["secrets", "vault", "keyring"] license = "MIT/Apache-2.0" repository = "https://github.com/mikelodder7/cryptex" readme = "README.md" -version = "2.4.0" +version = "2.5.0" # `all-features` is not used: the browser-only features (web-storage, # indexeddb, opfs, js) are rejected on non-wasm targets on purpose. diff --git a/README.md b/README.md index b940f92..7d8c56a 100644 --- a/README.md +++ b/README.md @@ -187,6 +187,7 @@ await keyring.close(); | `"turso"` (default) | `"indexeddb"` (default) | the encrypted database image, saved after every change | | `"turso"` | `"opfs"` | the database file itself, in the origin private file system | | `"turso"` | `"memory"` | nothing; `export()` the image yourself | +| `"memory"` | `"indexeddb"` | the sealed image, saved after every change | | `"memory"` | `"localstorage"` | a sealed blob under `localStorage["cryptex:"]` | | `"memory"` | `"memory"` | nothing | diff --git a/src/error.rs b/src/error.rs index faf25f0..50180bd 100644 --- a/src/error.rs +++ b/src/error.rs @@ -124,18 +124,10 @@ impl From for KeyRingError { } /// Browser APIs report failures as thrown JavaScript values. -#[cfg(any( - feature = "indexeddb", - feature = "opfs", - feature = "web-storage" -))] +#[cfg(any(feature = "indexeddb", feature = "opfs", feature = "web-storage"))] #[cfg_attr( docsrs, - doc(cfg(any( - feature = "indexeddb", - feature = "opfs", - feature = "web-storage" - ))) + doc(cfg(any(feature = "indexeddb", feature = "opfs", feature = "web-storage"))) )] impl From for KeyRingError { fn from(value: wasm_bindgen::JsValue) -> Self { diff --git a/src/keyring.rs b/src/keyring.rs index 18acdda..0cb150a 100644 --- a/src/keyring.rs +++ b/src/keyring.rs @@ -22,10 +22,10 @@ pub mod encrypted_vfs; feature = "turso-encrypted-io" ))] pub mod file_common; -#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] -pub mod kms; #[cfg(feature = "indexeddb")] pub mod indexeddb; +#[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] +pub mod kms; #[cfg(all(target_os = "linux", feature = "linux-secret-service"))] pub mod linux; #[cfg(all(target_os = "macos", feature = "macos-keychain"))] @@ -55,10 +55,10 @@ mod turso_common; pub mod turso_encrypted_io; #[cfg(feature = "turso")] mod turso_web; -#[cfg(any(feature = "opfs", feature = "turso"))] -mod web_time; #[cfg(feature = "web-storage")] pub mod web_storage; +#[cfg(any(feature = "opfs", feature = "turso"))] +mod web_time; #[cfg(all(target_os = "windows", feature = "windows-credentials"))] pub mod windows; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs index 2a211da..c5dbc73 100644 --- a/src/keyring/indexeddb.rs +++ b/src/keyring/indexeddb.rs @@ -32,8 +32,8 @@ use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::JsFuture; use web_sys::{IdbDatabase, IdbFactory, IdbRequest, IdbTransaction, IdbTransactionMode}; -use crate::error::KeyRingError; use crate::Result; +use crate::error::KeyRingError; /// Database holding every keyring image for this origin. const DB_NAME: &str = "cryptex"; @@ -79,7 +79,11 @@ impl SnapshotStore { /// Read the stored image, if there is one. pub async fn load(&self) -> Result>> { let tx = self.transaction(IdbTransactionMode::Readonly)?; - let value = await_request(&tx.object_store(STORE_NAME)?.get(&JsValue::from_str(&self.name))?).await?; + let value = await_request( + &tx.object_store(STORE_NAME)? + .get(&JsValue::from_str(&self.name))?, + ) + .await?; drop(tx); if value.is_undefined() || value.is_null() { Ok(None) @@ -142,7 +146,8 @@ impl LockHold { .map_err(|_| unsupported("the Web Locks API is not callable"))?; let options = js_sys::Object::new(); - Reflect::set(&options, &JsValue::from_str("ifAvailable"), &JsValue::TRUE).map_err(js_error)?; + Reflect::set(&options, &JsValue::from_str("ifAvailable"), &JsValue::TRUE) + .map_err(js_error)?; // `release` settles the promise the callback returns, ending the lock. let release: std::rc::Rc>> = @@ -237,9 +242,7 @@ async fn open_db() -> Result { .map_err(js_error)? .dyn_into() .map_err(|_| unsupported("this browser has no IndexedDB"))?; - let request = factory - .open_with_u32(DB_NAME, 1) - .map_err(js_error)?; + let request = factory.open_with_u32(DB_NAME, 1).map_err(js_error)?; // Create the object store the first time the database is opened. let upgrade_request = request.clone(); @@ -288,7 +291,12 @@ async fn await_request(request: &IdbRequest) -> Result { let request = request.clone(); let reject = reject.clone(); Closure::::once_into_js(move |_event: JsValue| { - let err = request.error().ok().flatten().map(JsValue::from).unwrap_or(JsValue::NULL); + let err = request + .error() + .ok() + .flatten() + .map(JsValue::from) + .unwrap_or(JsValue::NULL); let _ = reject.call1(&JsValue::NULL, &err); }) }; diff --git a/src/keyring/opfs.rs b/src/keyring/opfs.rs index 86ddb12..3ee3b64 100644 --- a/src/keyring/opfs.rs +++ b/src/keyring/opfs.rs @@ -32,10 +32,12 @@ use super::page_store::PageStore; use super::web_time::WebClock; -use ::turso::core::io::FileId; -use ::turso::core::{Clock, File as TursoFileIo, LimboError, MonotonicInstant, WallClockInstant, io_error}; -use crate::error::KeyRingError; use crate::Result; +use crate::error::KeyRingError; +use ::turso::core::io::FileId; +use ::turso::core::{ + Clock, File as TursoFileIo, LimboError, MonotonicInstant, WallClockInstant, io_error, +}; use std::cell::{Cell, RefCell}; use std::collections::HashMap; use std::io; @@ -69,13 +71,12 @@ impl OpfsPages { let directory = open_directory().await?; let options = FileSystemGetFileOptions::new(); options.set_create(true); - let handle: web_sys::FileSystemFileHandle = JsFuture::from( - directory.get_file_handle_with_options(name, &options), - ) - .await - .map_err(js_error)? - .dyn_into() - .map_err(js_error)?; + let handle: web_sys::FileSystemFileHandle = + JsFuture::from(directory.get_file_handle_with_options(name, &options)) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; let access: FileSystemSyncAccessHandle = JsFuture::from(handle.create_sync_access_handle()) @@ -194,7 +195,7 @@ impl OpfsIo { Ok(Self { files }) } - /// Flush both files to disk and release their handles. + /// Flush both files to disk and release their handles. pub(crate) fn close(&mut self) { for file in self.files.values() { file.close(); @@ -354,9 +355,11 @@ impl TursoFileIo for OpfsFile { } async fn open_directory() -> Result { - let navigator = - js_sys::Reflect::get(&js_sys::global(), &wasm_bindgen::JsValue::from_str("navigator")) - .map_err(js_error)?; + let navigator = js_sys::Reflect::get( + &js_sys::global(), + &wasm_bindgen::JsValue::from_str("navigator"), + ) + .map_err(js_error)?; let storage = js_sys::Reflect::get(&navigator, &wasm_bindgen::JsValue::from_str("storage")) .map_err(js_error)?; if storage.is_undefined() { @@ -364,13 +367,11 @@ async fn open_directory() -> Result { "this browser has no Storage Manager API, so OPFS is unavailable", )); } - let get_directory = js_sys::Reflect::get( - &storage, - &wasm_bindgen::JsValue::from_str("getDirectory"), - ) - .map_err(js_error)? - .dyn_into::() - .map_err(js_error)?; + let get_directory = + js_sys::Reflect::get(&storage, &wasm_bindgen::JsValue::from_str("getDirectory")) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?; let root: FileSystemDirectoryHandle = JsFuture::from( get_directory .call0(&storage) @@ -385,13 +386,11 @@ async fn open_directory() -> Result { let options = FileSystemGetDirectoryOptions::new(); options.set_create(true); - let directory = JsFuture::from( - root.get_directory_handle_with_options(DIRECTORY, &options), - ) - .await - .map_err(js_error)? - .dyn_into() - .map_err(js_error)?; + let directory = JsFuture::from(root.get_directory_handle_with_options(DIRECTORY, &options)) + .await + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; Ok(directory) } diff --git a/src/keyring/page_cipher.rs b/src/keyring/page_cipher.rs index 97a3b83..0e81dd0 100644 --- a/src/keyring/page_cipher.rs +++ b/src/keyring/page_cipher.rs @@ -167,7 +167,10 @@ pub(crate) fn logical_size(store: &S) -> io::Result } /// Truncate an encrypted store to hold `logical_size` bytes (rounded up to a page). -pub(crate) fn truncate(store: &mut S, logical_size: usize) -> io::Result<()> { +pub(crate) fn truncate( + store: &mut S, + logical_size: usize, +) -> io::Result<()> { let num_pages = logical_size.div_ceil(LOGICAL_PAGE_SIZE); store.set_len((num_pages * PHYSICAL_PAGE_SIZE) as u64) } @@ -266,6 +269,9 @@ mod tests { truncate(&mut f, 1).unwrap(); assert_eq!(logical_size(&f).unwrap(), LOGICAL_PAGE_SIZE as u64); + // Close the file before removing it, for Windows. + f.sync_all().unwrap(); + #[allow(clippy::drop_non_drop)] drop(f); let _ = fs::remove_file(path); } diff --git a/src/keyring/page_store.rs b/src/keyring/page_store.rs index 2641bbd..08304df 100644 --- a/src/keyring/page_store.rs +++ b/src/keyring/page_store.rs @@ -84,7 +84,8 @@ impl PageStore for MemPages { } fn read_exact_at(&mut self, offset: u64, buf: &mut [u8]) -> io::Result<()> { - let start = usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + let start = + usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; let end = start .checked_add(buf.len()) .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; @@ -101,7 +102,8 @@ impl PageStore for MemPages { } fn write_all_at(&mut self, offset: u64, buf: &[u8]) -> io::Result<()> { - let start = usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; + let start = + usize::try_from(offset).map_err(|_| io::Error::from(io::ErrorKind::InvalidInput))?; let end = start .checked_add(buf.len()) .ok_or_else(|| io::Error::from(io::ErrorKind::InvalidInput))?; @@ -122,4 +124,3 @@ impl PageStore for MemPages { Ok(()) } } - diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 305da43..380e9c3 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -15,9 +15,9 @@ use std::sync::Arc; use zeroize::{Zeroize, Zeroizing}; use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_file}; -use super::turso_common::TursoFile; #[cfg(feature = "opfs")] use super::opfs::OpfsIo; +use super::turso_common::TursoFile; use super::turso_web::{WebIo, unique_db_path}; use crate::error::KeyRingError; diff --git a/src/keyring/turso_web.rs b/src/keyring/turso_web.rs index ebe5157..e11cde4 100644 --- a/src/keyring/turso_web.rs +++ b/src/keyring/turso_web.rs @@ -18,14 +18,14 @@ use super::page_store::{MemPages, PageStore}; use super::web_time::WebClock; +use crate::Result; +use crate::error::KeyRingError; use ::turso::core::io::FileId; use ::turso::core::io::FileSyncType; use ::turso::core::{ Buffer, Clock, Completion, File as TursoFileIo, IO, LimboError, MonotonicInstant, OpenFlags, WallClockInstant, io_error, }; -use crate::error::KeyRingError; -use crate::Result; use std::collections::HashMap; use std::sync::{Arc, Mutex, MutexGuard}; @@ -50,10 +50,7 @@ impl WebIo { /// The path of the database file in this IO, if it has one. pub(crate) fn db_path(&self) -> Option { let files = self.files.lock().ok()?; - files - .keys() - .find(|path| path.ends_with(".db3")) - .cloned() + files.keys().find(|path| path.ends_with(".db3")).cloned() } /// Copy every file into one blob. diff --git a/src/keyring/web_storage.rs b/src/keyring/web_storage.rs index 393c346..a6c8d5d 100644 --- a/src/keyring/web_storage.rs +++ b/src/keyring/web_storage.rs @@ -32,10 +32,10 @@ use super::cipher::CipherAlgorithm; use super::file_common; use super::memory::MemoryKeyring; -use crate::error::KeyRingError; -use wasm_bindgen::JsCast; use crate::KeyRingSecret; +use crate::error::KeyRingError; use crate::{DynKeyRing, NewKeyRing, Result}; +use wasm_bindgen::JsCast; /// Connection parameters for [`WebStorageKeyring`]. pub type ConnectionParams = file_common::ConnectionParams; @@ -195,12 +195,15 @@ pub async fn request_persistent_storage() -> Result { .ok_or_else(|| KeyRingError::GeneralError { msg: "this browser has no Storage Manager API".to_string(), })?; - let persist = js_sys::Reflect::get(&storage_manager, &wasm_bindgen::JsValue::from_str("persist")) - .map_err(js_error)? - .dyn_into::() - .map_err(|_| KeyRingError::GeneralError { - msg: "this browser cannot persist storage".to_string(), - })?; + let persist = js_sys::Reflect::get( + &storage_manager, + &wasm_bindgen::JsValue::from_str("persist"), + ) + .map_err(js_error)? + .dyn_into::() + .map_err(|_| KeyRingError::GeneralError { + msg: "this browser cannot persist storage".to_string(), + })?; let granted = persist .call0(&storage_manager) .map_err(js_error)? diff --git a/src/lib.rs b/src/lib.rs index 9e08558..738e57a 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -34,6 +34,10 @@ pub use keyring::encrypted_vfs; ))) )] pub use keyring::file_common; +#[cfg(feature = "memory")] +#[cfg_attr(docsrs, doc(cfg(feature = "memory")))] +#[cfg(feature = "indexeddb")] +pub use keyring::indexeddb; #[cfg(any(feature = "yubihsm-usb", feature = "yubihsm-http"))] #[cfg_attr( docsrs, @@ -50,19 +54,12 @@ pub use keyring::linux; #[cfg_attr(docsrs, doc(cfg(all(target_os = "macos", feature = "macos-keychain"))))] pub use keyring::macos; #[cfg(feature = "memory")] -#[cfg_attr(docsrs, doc(cfg(feature = "memory")))] -#[cfg(feature = "indexeddb")] -pub use keyring::indexeddb; -#[cfg(feature = "memory")] pub use keyring::memory; #[cfg(feature = "web-storage")] pub use keyring::web_storage; #[cfg(feature = "js")] mod wasm; -#[cfg(feature = "js")] -#[cfg_attr(docsrs, doc(cfg(feature = "js")))] -pub use wasm::{Keyring, request_persistent_storage}; #[cfg(feature = "file")] #[cfg_attr(docsrs, doc(cfg(feature = "file")))] pub use keyring::sqlcipher; @@ -85,6 +82,9 @@ pub use keyring::windows; )] pub use keyring::yubihsm; pub use keyring::*; +#[cfg(feature = "js")] +#[cfg_attr(docsrs, doc(cfg(feature = "js")))] +pub use wasm::{Keyring, request_persistent_storage}; #[cfg(any( all(target_os = "macos", feature = "macos-keychain"), diff --git a/src/wasm.rs b/src/wasm.rs index f52e0b9..3ad6fa9 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -47,12 +47,12 @@ use js_sys::Reflect; use wasm_bindgen::prelude::*; use zeroize::Zeroizing; +use crate::DynKeyRing; use crate::error::KeyRingError; use crate::indexeddb::SnapshotStore; use crate::memory::MemoryKeyring; use crate::turso::TursoKeyring; use crate::web_storage::{self, LocalStorageImage}; -use crate::DynKeyRing; /// A keyring, opened from JavaScript. #[wasm_bindgen] @@ -116,8 +116,8 @@ impl Keyring { let options = Options::parse(options)?; match options.backend { Backend::Turso => { - let keyring = TursoKeyring::from_bytes(image, &turso_params(connection)?) - .map_err(js)?; + let keyring = + TursoKeyring::from_bytes(image, &turso_params(connection)?).map_err(js)?; Ok(Keyring { inner: Inner::Turso { keyring: Some(keyring), @@ -143,9 +143,7 @@ impl Keyring { /// Read a secret. Throws `ItemNotFound` when there is none. pub fn get(&mut self, id: &str) -> Result, JsError> { let secret = match &mut self.inner { - Inner::Turso { keyring, .. } => { - keyring.as_mut().ok_or_else(closed)?.get_secret(id) - } + Inner::Turso { keyring, .. } => keyring.as_mut().ok_or_else(closed)?.get_secret(id), Inner::Memory { keyring, .. } => keyring.get_secret(id), } .map_err(js)?; @@ -354,7 +352,10 @@ async fn open_memory(connection: &str, name: &str, store: StoreKind) -> Result (MemoryKeyring::with_params(¶ms).map_err(js)?, Store::None), + StoreKind::Memory => ( + MemoryKeyring::with_params(¶ms).map_err(js)?, + Store::None, + ), // Refused when the options are parsed; OPFS stores database files. StoreKind::Opfs => { return Err(JsError::new( @@ -455,8 +456,8 @@ impl Options { } fn string_property(value: &JsValue, name: &str) -> Result, JsError> { - let property = Reflect::get(value, &JsValue::from_str(name)) - .map_err(|e| js(KeyRingError::from(e)))?; + let property = + Reflect::get(value, &JsValue::from_str(name)).map_err(|e| js(KeyRingError::from(e)))?; if property.is_undefined() || property.is_null() { return Ok(None); } diff --git a/tests/wasm.rs b/tests/wasm.rs index 4c60ea9..2c2d895 100644 --- a/tests/wasm.rs +++ b/tests/wasm.rs @@ -7,7 +7,7 @@ //! Run with `wasm-pack test --headless --chrome --no-default-features //! --features js`. Native `cargo test` skips this file. -#![cfg(all(target_family = "wasm", target_os = "unknown"))] +#![cfg(all(target_family = "wasm", target_os = "unknown", feature = "js"))] use cryptex::Keyring; use wasm_bindgen_test::wasm_bindgen_test; From e1e90ca1d4d3480d53c905fb0f758b10f4841e23 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 16:02:57 -0500 Subject: [PATCH 09/18] Fix the browser example's connection string and error check The example pre-filled a password with spaces, which the whitespace-separated connection string cannot carry, so Open failed with a parser byte offset. Use a password without spaces and say why if one is typed. Reading a missing secret then failed loudly too: the kind is in error.message, not in String(error), which prepends "Error: ". --- examples/web/index.html | 2 +- examples/web/main.js | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/examples/web/index.html b/examples/web/index.html index df53d34..9e7f4de 100644 --- a/examples/web/index.html +++ b/examples/web/index.html @@ -67,7 +67,7 @@

cryptex in the browser

Keyring - + diff --git a/examples/web/main.js b/examples/web/main.js index 9ce341b..d1e203d 100644 --- a/examples/web/main.js +++ b/examples/web/main.js @@ -19,6 +19,11 @@ function show(message) { function connection() { const password = $("password").value; if (!password) throw new Error("Enter a password first"); + // The connection string is whitespace-separated, so a value cannot contain + // one; say so rather than passing the parser's byte offset to the user. + if (/\s/.test(password)) { + throw new Error("The password cannot contain spaces; the connection string is `password= salt=`"); + } return `password=${password} salt=cryptex-browser-example`; } @@ -50,7 +55,8 @@ $("open").addEventListener("click", () => keyring.get(id); ids.push(id); } catch (error) { - if (!String(error).startsWith("ItemNotFound")) throw error; + // `String(error)` would prepend "Error: "; the kind is in `message`. + if (!error.message.startsWith("ItemNotFound")) throw error; } } if (ids.length) show(`Opened "${$("name").value}"; it holds ${ids.join(", ")}.`); From 3a76843968db9fee91a1c526ff9d0de8335a2f44 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 16:25:14 -0500 Subject: [PATCH 10/18] List keyrings and the keys inside them The page could read a secret but not ask a keyring what it holds. Add TursoKeyring::keys and MemoryKeyring::keys, and SnapshotStore::list_names, which reads IndexedDB without taking the lock, then expose them to JavaScript as keyring.keys() and storedKeyrings(). The example page shows both lists and opens a keyring when its name is clicked. --- examples/web/index.html | 37 +++++++++++++++ examples/web/main.js | 95 ++++++++++++++++++++++++++++++++----- src/keyring/file_common.rs | 2 + src/keyring/indexeddb.rs | 20 ++++++++ src/keyring/memory.rs | 16 +++++++ src/keyring/turso.rs | 6 +++ src/keyring/turso_common.rs | 24 ++++++++-- src/lib.rs | 2 +- src/wasm.rs | 17 +++++++ tests/wasm.rs | 21 ++++++++ 10 files changed, 223 insertions(+), 17 deletions(-) diff --git a/examples/web/index.html b/examples/web/index.html index 9e7f4de..0114607 100644 --- a/examples/web/index.html +++ b/examples/web/index.html @@ -53,6 +53,29 @@ font-size: 0.85rem; opacity: 0.75; } + .list { + list-style: none; + margin: 0; + padding: 0; + font-family: ui-monospace, monospace; + font-size: 0.9rem; + } + .list li { + padding: 0.15rem 0; + } + .list .open { + opacity: 0.75; + } + button.link { + background: none; + border: none; + margin: 0; + padding: 0; + font: inherit; + color: inherit; + text-decoration: underline; + cursor: pointer; + } @@ -86,6 +109,20 @@

cryptex in the browser

+
+ Keyrings in this browser +
    +
  • Loading…
  • +
+
+ +
+ Keys in the open keyring +
    +
  • Open a keyring to see its keys.
  • +
+
+

Not opened.

diff --git a/examples/web/main.js b/examples/web/main.js index d1e203d..971af65 100644 --- a/examples/web/main.js +++ b/examples/web/main.js @@ -5,9 +5,14 @@ // Then serve this directory over http (not file://): // python3 -m http.server -d examples/web 8080 -import init, { Keyring, requestPersistentStorage } from "./pkg/cryptex.js"; +import init, { + Keyring, + requestPersistentStorage, + storedKeyrings, +} from "./pkg/cryptex.js"; const $ = (id) => document.getElementById(id); +const decoder = new TextDecoder(); let keyring = null; @@ -15,6 +20,74 @@ function show(message) { $("status").textContent = message; } +function render(list, empty, rows) { + list.replaceChildren(); + if (!rows.length) { + const item = document.createElement("li"); + item.className = "hint"; + item.textContent = empty; + list.append(item); + return; + } + list.append(...rows); +} + +/** One entry per keyring in IndexedDB; clicking it opens that keyring. */ +function keyringRow(name) { + const item = document.createElement("li"); + const button = document.createElement("button"); + button.className = "link"; + button.textContent = name; + button.addEventListener("click", () => + guarded(async () => { + $("name").value = name; + await open(); + await refresh(); + }), + ); + item.append(button); + if (keyring && name === $("name").value) { + const open = document.createElement("span"); + open.className = "open"; + open.textContent = " (open)"; + item.append(open); + } + return item; +} + +/** One entry per key in the open keyring, with its value. */ +function keyRow(id) { + const item = document.createElement("li"); + const name = document.createElement("code"); + name.textContent = id; + const value = document.createElement("span"); + try { + value.textContent = ` = ${decoder.decode(keyring.get(id))}`; + } catch (error) { + value.textContent = ` (${error.message})`; + } + item.append(name, value); + return item; +} + +async function refreshKeyrings() { + const names = await storedKeyrings(); + render($("keyrings"), "None stored yet.", names.map(keyringRow)); +} + +async function refreshKeys() { + if (!keyring) { + render($("keys"), "Open a keyring to see its keys.", []); + return; + } + render($("keys"), "This keyring holds no keys.", keyring.keys().map(keyRow)); +} + +async function refresh() { + await refreshKeyrings(); + await refreshKeys(); +} + /** Connection strings are `password=... salt=...`. */ function connection() { const password = $("password").value; @@ -48,18 +121,9 @@ async function guarded(action) { $("open").addEventListener("click", () => guarded(async () => { await open(); - const ids = []; - // Reading a secret that is not there is an error, not an empty value. - for (const id of ["api-token"]) { - try { - keyring.get(id); - ids.push(id); - } catch (error) { - // `String(error)` would prepend "Error: "; the kind is in `message`. - if (!error.message.startsWith("ItemNotFound")) throw error; - } - } - if (ids.length) show(`Opened "${$("name").value}"; it holds ${ids.join(", ")}.`); + await refresh(); + const count = keyring.keys().length; + show(`Opened "${$("name").value}"; it holds ${count} key${count === 1 ? "" : "s"}.`); }), ); @@ -79,6 +143,7 @@ $("set").addEventListener("click", () => guarded(async () => { if (!keyring) throw new Error("Open the keyring first"); await keyring.set($("id").value, new TextEncoder().encode($("value").value)); + await refreshKeys(); show(`Stored "${$("id").value}". It is on disk, encrypted, before this line ran.`); }), ); @@ -95,6 +160,7 @@ $("delete").addEventListener("click", () => guarded(async () => { if (!keyring) throw new Error("Open the keyring first"); await keyring.delete($("id").value); + await refreshKeys(); show(`Deleted "${$("id").value}".`); }), ); @@ -108,3 +174,6 @@ $("export").addEventListener("click", () => show(`Copied ${image.length} encrypted bytes to the clipboard.`); }), ); +// Show what the origin already holds before anything is opened. +await init(); +await guarded(refresh); diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 46b8d24..3da30aa 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -72,6 +72,8 @@ pub(crate) const UPSERT_SECRET_SQL: &str = "INSERT INTO secrets(id, value) VALUE feature = "turso-encrypted-io" ))] pub(crate) const DELETE_SECRET_SQL: &str = "DELETE FROM secrets WHERE id = ?1"; +#[cfg(any(feature = "turso", feature = "turso-encrypted-io"))] +pub(crate) const SELECT_IDS_SQL: &str = "SELECT id FROM secrets ORDER BY id"; #[cfg(any( feature = "file", diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs index c5dbc73..416cf1e 100644 --- a/src/keyring/indexeddb.rs +++ b/src/keyring/indexeddb.rs @@ -110,6 +110,26 @@ impl SnapshotStore { await_transaction(&tx).await } + /// Every keyring stored in this origin's IndexedDB, in name order. + /// + /// Reads without taking a lock, so it is safe to call while another tab + /// holds a keyring open. + pub async fn list_names() -> Result> { + let db = open_db().await?; + let tx = db + .transaction_with_str_and_mode(STORE_NAME, IdbTransactionMode::Readonly) + .map_err(js_error)?; + let store = tx.object_store(STORE_NAME)?; + let keys = await_request(&store.get_all_keys()?).await?; + drop(tx); + let mut names: Vec = js_sys::Array::from(&keys) + .iter() + .filter_map(|key| key.as_string()) + .collect(); + names.sort(); + Ok(names) + } + fn transaction(&self, mode: IdbTransactionMode) -> Result { self.db .transaction_with_str_and_mode(STORE_NAME, mode) diff --git a/src/keyring/memory.rs b/src/keyring/memory.rs index f231f05..0b5a25c 100644 --- a/src/keyring/memory.rs +++ b/src/keyring/memory.rs @@ -351,6 +351,11 @@ impl MemoryKeyring { Ok(blob) } + /// Every id in the keyring, in order. + pub fn keys(&self) -> Vec { + self.secrets.keys().cloned().collect() + } + /// Re-encrypt under new connection parameters, optionally with a new cipher. /// /// The secrets stay in memory; only the key, salt and cipher change, so @@ -447,6 +452,17 @@ mod tests { assert_eq!(reopened.get_secret("c").unwrap().as_slice(), b"three"); } + #[test] + fn keys_lists_the_ids_in_order() { + let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); + assert!(kr.keys().is_empty()); + kr.set_secret("b", b"two").unwrap(); + kr.set_secret("a", b"one").unwrap(); + assert_eq!(kr.keys(), ["a", "b"]); + kr.delete_secret("a").unwrap(); + assert_eq!(kr.keys(), ["b"]); + } + #[test] fn empty_keyring_round_trips() { let kr = MemoryKeyring::with_params(&password_params("")).unwrap(); diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index 380e9c3..db67222 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -223,6 +223,11 @@ impl TursoKeyring { .snapshot() } + /// Every id in the keyring, in order. + pub fn keys(&self) -> Result> { + self.file.ids() + } + /// Re-encrypt the keyring with a new key (and optionally a different cipher). /// /// Consumes the keyring and returns it reopened under `new_params`. If @@ -321,6 +326,7 @@ mod tests { let mut restored = TursoKeyring::from_bytes(&image, &p).unwrap(); assert_eq!(restored.get_secret("k1").unwrap().0, b"value1"); assert_eq!(restored.get_secret("shared").unwrap().0, b"kept"); + assert_eq!(restored.keys().unwrap(), ["k1", "shared"]); assert!(matches!( TursoKeyring::from_bytes(&image, &wrong), diff --git a/src/keyring/turso_common.rs b/src/keyring/turso_common.rs index 83e27e6..55b61bd 100644 --- a/src/keyring/turso_common.rs +++ b/src/keyring/turso_common.rs @@ -23,9 +23,9 @@ use std::task::{Context, Poll, Waker}; use std::thread::{self, Thread}; use super::file_common::{ - CREATE_SECRETS_SQL, DELETE_SECRET_SQL, SELECT_SECRET_SQL, SecretStore, UPSERT_SECRET_SQL, - VERIFY_KEY_SQL, acquire_single_opener_lock, decode_secret, get_keyring_file, invalid_key, - sibling_path, + CREATE_SECRETS_SQL, DELETE_SECRET_SQL, SELECT_IDS_SQL, SELECT_SECRET_SQL, SecretStore, + UPSERT_SECRET_SQL, VERIFY_KEY_SQL, acquire_single_opener_lock, decode_secret, get_keyring_file, + invalid_key, sibling_path, }; use crate::error::KeyRingError; use zeroize::Zeroizing; @@ -146,6 +146,17 @@ impl TursoStore { Ok(()) } + fn ids(&self) -> Result> { + block_on::<_, Vec, KeyRingError>(async { + let mut rows = self.conn.query(SELECT_IDS_SQL, ()).await?; + let mut ids = Vec::new(); + while let Some(row) = rows.next().await? { + ids.push(row.get::(0)?); + } + Ok(ids) + }) + } + fn delete(&self, id: &str) -> Result<()> { block_on(self.conn.execute(DELETE_SECRET_SQL, [id]))?; Ok(()) @@ -305,6 +316,13 @@ impl TursoFile { } } +impl TursoFile { + /// Every id in the keyring, in order. + pub(crate) fn ids(&self) -> Result> { + self.store.ids() + } +} + impl SecretStore for TursoFile { fn get(&self, id: &str) -> Result { self.store.get(id) diff --git a/src/lib.rs b/src/lib.rs index 738e57a..a3a96a5 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -84,7 +84,7 @@ pub use keyring::yubihsm; pub use keyring::*; #[cfg(feature = "js")] #[cfg_attr(docsrs, doc(cfg(feature = "js")))] -pub use wasm::{Keyring, request_persistent_storage}; +pub use wasm::{Keyring, request_persistent_storage, stored_keyrings}; #[cfg(any( all(target_os = "macos", feature = "macos-keychain"), diff --git a/src/wasm.rs b/src/wasm.rs index 3ad6fa9..083e55c 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -246,6 +246,14 @@ impl Keyring { } } + /// Every id in this keyring, in order. + pub fn keys(&self) -> Result, JsError> { + match &self.inner { + Inner::Turso { keyring, .. } => keyring.as_ref().ok_or_else(closed)?.keys().map_err(js), + Inner::Memory { keyring, .. } => Ok(keyring.keys()), + } + } + /// Copy the encrypted image out, e.g. to move it to another store. pub fn export(&self) -> Result, JsError> { match &self.inner { @@ -298,6 +306,15 @@ pub async fn request_persistent_storage() -> Result { web_storage::request_persistent_storage().await.map_err(js) } +/// Every keyring IndexedDB holds for this origin, in name order. +/// +/// Works without opening anything, so a page can list what is stored before +/// the user picks one. +#[wasm_bindgen(js_name = "storedKeyrings")] +pub async fn stored_keyrings() -> Result, JsError> { + SnapshotStore::list_names().await.map_err(js) +} + async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result { let params = turso_params(connection)?; let (keyring, store) = match store { diff --git a/tests/wasm.rs b/tests/wasm.rs index 2c2d895..95406db 100644 --- a/tests/wasm.rs +++ b/tests/wasm.rs @@ -58,6 +58,27 @@ async fn indexeddb_keeps_the_secrets() { reopened.close().await.expect("close succeeds"); } +#[wasm_bindgen_test] +async fn keys_and_keyring_names_are_listed() { + let name = unique_name("keys"); + let mut keyring = Keyring::open(CONNECTION, &name, Default::default()) + .await + .expect("a keyring opens"); + + keyring.set("b", b"two").await.expect("set succeeds"); + keyring.set("a", b"one").await.expect("set succeeds"); + assert_eq!( + keyring.keys().expect("keys succeeds"), + ["a".to_string(), "b".to_string()] + ); + + // A page can list what is stored without opening anything. + let stored = cryptex::stored_keyrings().await.expect("the store lists"); + assert!(stored.contains(&name)); + + keyring.close().await.expect("close succeeds"); +} + #[wasm_bindgen_test] async fn a_wrong_password_is_refused() { let name = unique_name("indexeddb"); From d0bf61551bb19fd39ac1874365e9a373943503b4 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 16:46:08 -0500 Subject: [PATCH 11/18] List keyrings in localStorage and OPFS too storedKeyrings now takes a store: IndexedDB is still the default, and localStorage and OPFS each have their own listing. Neither reads an image, so both are safe while a tab holds the keyring open, and listing OPFS works from a page even though opening one needs a worker. The example page shows all three stores, tags each row with the store it came from, and can open a keyring from either store the page can reach. --- README.md | 5 ++ examples/web/index.html | 26 ++++++++-- examples/web/main.js | 97 ++++++++++++++++++++++++++------------ src/keyring/opfs.rs | 50 ++++++++++++++++++++ src/keyring/web_storage.rs | 23 +++++++++ src/wasm.rs | 17 +++++-- tests/wasm.rs | 50 +++++++++++++++++++- 7 files changed, 228 insertions(+), 40 deletions(-) diff --git a/README.md b/README.md index 7d8c56a..e055d26 100644 --- a/README.md +++ b/README.md @@ -194,6 +194,11 @@ await keyring.close(); `import(connection, image, options)` reopens an image returned by `export()`, and `rekey(connection)` changes its password. +`keyring.keys()` lists the ids inside an open keyring, and +`storedKeyrings({ store })` lists the keyrings the origin already has in +`"indexeddb"` (the default), `"localstorage"` or `"opfs"`, without opening +anything. Listing OPFS works from a page; opening an OPFS keyring does not. + Every store keeps the data encrypted; the key comes from the password (or raw key) in the connection string, so a store with the wrong connection string fails with `AccessDenied` instead of returning garbage. diff --git a/examples/web/index.html b/examples/web/index.html index 0114607..0cf20d3 100644 --- a/examples/web/index.html +++ b/examples/web/index.html @@ -4,6 +4,7 @@ cryptex in the browser +

cryptex in the browser

- The keyring is a Turso database kept in IndexedDB. Everything you store is - encrypted with a key derived from the password; any script on this origin - can read the ciphertext, so pick a password you would not reuse - carelessly. + A keyring is a Turso database, either kept in IndexedDB (one image per + keyring) or in localStorage. Everything you store is encrypted with a key + derived from the password; any script on this origin can read the + ciphertext, so pick a password you would not reuse carelessly.

@@ -93,6 +106,11 @@

cryptex in the browser

+ +
diff --git a/examples/web/main.js b/examples/web/main.js index 971af65..842c25b 100644 --- a/examples/web/main.js +++ b/examples/web/main.js @@ -1,9 +1,11 @@ -// A browser page that keeps a cryptex keyring in IndexedDB. +// A browser page that keeps cryptex keyrings in IndexedDB or localStorage. // // Build first: -// wasm-pack build --target web --out-dir examples/web/pkg -- --no-default-features --features js +// wasm-pack build --target web --out-dir examples/web/pkg --no-default-features --features js // Then serve this directory over http (not file://): // python3 -m http.server -d examples/web 8080 +// +// OPFS keyrings are listed too, but opening one needs a worker: see worker.js. import init, { Keyring, @@ -14,42 +16,67 @@ import init, { const $ = (id) => document.getElementById(id); const decoder = new TextDecoder(); +/** The stores this page can open. OPFS needs the worker in worker.js. */ +const STORES = ["indexeddb", "localstorage"]; +/** Every store the page lists, including the one it cannot open here. */ +const LISTED_STORES = [...STORES, "opfs"]; + let keyring = null; +/** Where the open keyring lives, so the list can mark it. */ +let current = null; function show(message) { $("status").textContent = message; } -function render(list, empty, rows) { - list.replaceChildren(); - if (!rows.length) { - const item = document.createElement("li"); - item.className = "hint"; - item.textContent = empty; - list.append(item); - return; - } - list.append(...rows); +function hint(message) { + const item = document.createElement("li"); + item.className = "hint"; + item.textContent = message; + return item; +} + +function render(list, rows) { + list.replaceChildren(...(rows.length ? rows : [hint("None stored.")])); } -/** One entry per keyring in IndexedDB; clicking it opens that keyring. */ -function keyringRow(name) { +/** One entry per keyring, tagged with the store it lives in. */ +function keyringRow(store, name) { const item = document.createElement("li"); + + const tag = document.createElement("span"); + tag.className = "store"; + tag.textContent = store; + item.append(tag); + const button = document.createElement("button"); button.className = "link"; button.textContent = name; + if (store === "opfs") { + // A sync access handle is worker-only, so the page cannot open this. + button.disabled = true; + const note = document.createElement("span"); + note.className = "hint"; + note.textContent = " opens in a worker"; + item.append(button, note); + return item; + } button.addEventListener("click", () => guarded(async () => { $("name").value = name; + $("store").value = store; await open(); await refresh(); + const count = keyring.keys().length; + show(`Opened "${name}" from ${store}; it holds ${count} key${count === 1 ? "" : "s"}.`); }), ); item.append(button); - if (keyring && name === $("name").value) { + + if (current && current.store === store && current.name === name) { const open = document.createElement("span"); open.className = "open"; - open.textContent = " (open)"; + open.textContent = "(open)"; item.append(open); } return item; @@ -71,16 +98,27 @@ function keyRow(id) { } async function refreshKeyrings() { - const names = await storedKeyrings(); - render($("keyrings"), "None stored yet.", names.map(keyringRow)); + const rows = []; + for (const store of LISTED_STORES) { + let names = []; + try { + names = await storedKeyrings({ store }); + } catch (error) { + rows.push(hint(`${store}: ${error.message}`)); + continue; + } + if (!names.length) rows.push(hint(`${store}: none`)); + for (const name of names) rows.push(keyringRow(store, name)); + } + render($("keyrings"), rows); } async function refreshKeys() { if (!keyring) { - render($("keys"), "Open a keyring to see its keys.", []); + render($("keys"), [hint("Open a keyring to see its keys.")]); return; } - render($("keys"), "This keyring holds no keys.", keyring.keys().map(keyRow)); + render($("keys"), keyring.keys().map(keyRow)); } async function refresh() { @@ -101,20 +139,19 @@ function connection() { } async function open() { - await init(); + const name = $("name").value; + const store = $("store").value; if (keyring) await keyring.close(); - keyring = await Keyring.open(connection(), $("name").value, { - backend: "turso", - store: "indexeddb", - }); - show(`Opened "${$("name").value}".`); + keyring = await Keyring.open(connection(), name, { backend: "turso", store }); + current = { store, name }; + show(`Opened "${name}" from ${store}.`); } async function guarded(action) { try { await action(); } catch (error) { - show(`${error}`); + show(`${error.message ?? error}`); } } @@ -129,7 +166,6 @@ $("open").addEventListener("click", () => $("persist").addEventListener("click", () => guarded(async () => { - await init(); const granted = await requestPersistentStorage(); show( granted @@ -144,7 +180,7 @@ $("set").addEventListener("click", () => if (!keyring) throw new Error("Open the keyring first"); await keyring.set($("id").value, new TextEncoder().encode($("value").value)); await refreshKeys(); - show(`Stored "${$("id").value}". It is on disk, encrypted, before this line ran.`); + show(`Stored "${$("id").value}". It is in ${current.store}, encrypted, before this line ran.`); }), ); @@ -152,7 +188,7 @@ $("get").addEventListener("click", () => guarded(async () => { if (!keyring) throw new Error("Open the keyring first"); const bytes = keyring.get($("id").value); - show(`${$("id").value} is ${new TextDecoder().decode(bytes)}`); + show(`${$("id").value} is ${decoder.decode(bytes)}`); }), ); @@ -174,6 +210,7 @@ $("export").addEventListener("click", () => show(`Copied ${image.length} encrypted bytes to the clipboard.`); }), ); + // Show what the origin already holds before anything is opened. await init(); await guarded(refresh); diff --git a/src/keyring/opfs.rs b/src/keyring/opfs.rs index 3ee3b64..cb3a37f 100644 --- a/src/keyring/opfs.rs +++ b/src/keyring/opfs.rs @@ -394,6 +394,56 @@ async fn open_directory() -> Result { Ok(directory) } +/// Names of every keyring stored under `cryptex/` in the origin's OPFS. +/// +/// Reads the directory listing only, so it works from a page even though +/// opening a keyring needs a worker (sync access handles are worker-only). +pub async fn list_names() -> Result> { + use wasm_bindgen::JsValue; + + let directory = open_directory().await?; + let keys: js_sys::Function = js_sys::Reflect::get(&directory, &JsValue::from_str("keys")) + .map_err(js_error)? + .dyn_into() + .map_err(|_| unsupported("this browser cannot list OPFS files"))?; + let iterator = keys.call0(&directory).map_err(js_error)?; + let next: js_sys::Function = js_sys::Reflect::get(&iterator, &JsValue::from_str("next")) + .map_err(js_error)? + .dyn_into() + .map_err(js_error)?; + + let mut names = Vec::new(); + loop { + // `keys()` is an async iterator: each step is a promise for + // `{ value, done }`. + let step = JsFuture::from( + next.call0(&iterator) + .map_err(js_error)? + .dyn_into::() + .map_err(js_error)?, + ) + .await + .map_err(js_error)?; + let done = js_sys::Reflect::get(&step, &JsValue::from_str("done")) + .map_err(js_error)? + .as_bool() + .unwrap_or(true); + if done { + break; + } + let value = js_sys::Reflect::get(&step, &JsValue::from_str("value")).map_err(js_error)?; + // Every keyring is `.db3`; the WAL next to it is not a keyring. + if let Some(name) = value + .as_string() + .and_then(|name| name.strip_suffix(".db3").map(str::to_string)) + { + names.push(name); + } + } + names.sort(); + Ok(names) +} + fn js_error(value: wasm_bindgen::JsValue) -> KeyRingError { KeyRingError::from(value) } diff --git a/src/keyring/web_storage.rs b/src/keyring/web_storage.rs index a6c8d5d..f279d31 100644 --- a/src/keyring/web_storage.rs +++ b/src/keyring/web_storage.rs @@ -215,6 +215,29 @@ pub async fn request_persistent_storage() -> Result { Ok(value.as_bool().unwrap_or(false)) } +/// Names of every keyring this origin keeps in `localStorage`. +/// +/// Reads the entry names only, never the images. A keyring entry is +/// `cryptex:`, the key [`LocalStorageImage`] writes for that name. +pub fn list_names() -> Result> { + const PREFIX: &str = "cryptex:"; + + let storage = storage()?; + let length = storage.length().map_err(js_error)?; + let mut names = Vec::new(); + for index in 0..length { + if let Some(name) = storage + .key(index) + .map_err(js_error)? + .and_then(|key| key.strip_prefix(PREFIX).map(str::to_string)) + { + names.push(name); + } + } + names.sort(); + Ok(names) +} + fn storage() -> Result { let window = web_sys::window().ok_or_else(|| KeyRingError::GeneralError { msg: "localStorage is not available here: it exists only on a page, not in a worker" diff --git a/src/wasm.rs b/src/wasm.rs index 083e55c..5a98560 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -306,13 +306,20 @@ pub async fn request_persistent_storage() -> Result { web_storage::request_persistent_storage().await.map_err(js) } -/// Every keyring IndexedDB holds for this origin, in name order. +/// The keyrings this origin already has in one store, in name order. /// -/// Works without opening anything, so a page can list what is stored before -/// the user picks one. +/// `storedKeyrings({ store })` reads `indexeddb` (the default), `localstorage` +/// or `opfs` without opening anything, so a page can show what is stored +/// before the user picks a keyring. Nothing is listed for `memory`, which +/// keeps no store of its own. #[wasm_bindgen(js_name = "storedKeyrings")] -pub async fn stored_keyrings() -> Result, JsError> { - SnapshotStore::list_names().await.map_err(js) +pub async fn stored_keyrings(options: JsValue) -> Result, JsError> { + match Options::parse(options)?.store { + StoreKind::IndexedDb => SnapshotStore::list_names().await.map_err(js), + StoreKind::LocalStorage => web_storage::list_names().map_err(js), + StoreKind::Opfs => crate::opfs::list_names().await.map_err(js), + StoreKind::Memory => Ok(Vec::new()), + } } async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result { diff --git a/tests/wasm.rs b/tests/wasm.rs index 95406db..891095b 100644 --- a/tests/wasm.rs +++ b/tests/wasm.rs @@ -73,12 +73,60 @@ async fn keys_and_keyring_names_are_listed() { ); // A page can list what is stored without opening anything. - let stored = cryptex::stored_keyrings().await.expect("the store lists"); + let stored = cryptex::stored_keyrings(wasm_bindgen::JsValue::UNDEFINED) + .await + .expect("the store lists"); assert!(stored.contains(&name)); keyring.close().await.expect("close succeeds"); } +#[wasm_bindgen_test] +async fn every_store_lists_its_keyrings() { + use wasm_bindgen::JsValue; + + let indexeddb = cryptex::stored_keyrings(JsValue::UNDEFINED) + .await + .expect("IndexedDB lists"); + assert!(indexeddb.is_sorted()); + + // localStorage is a page API, so this test also covers the page case. + let name = unique_name("localstorage"); + let mut keyring = Keyring::open( + CONNECTION, + &name, + js_sys::JSON::parse(r#"{"backend":"turso","store":"localstorage"}"#) + .expect("the options are JSON"), + ) + .await + .expect("a localStorage keyring opens"); + keyring.set("token", b"value").await.expect("set succeeds"); + keyring.close().await.expect("close succeeds"); + + let listed = cryptex::stored_keyrings( + js_sys::JSON::parse(r#"{"store":"localstorage"}"#).expect("the options are JSON"), + ) + .await + .expect("localStorage lists"); + assert!(listed.contains(&name), "{listed:?} lacks {name}"); + + // OPFS listing reads the directory, which works from a page even though + // opening an OPFS keyring needs a worker. + let opfs = cryptex::stored_keyrings( + js_sys::JSON::parse(r#"{"store":"opfs"}"#).expect("the options are JSON"), + ) + .await + .expect("OPFS lists"); + assert!(opfs.is_sorted()); + + let memory = cryptex::stored_keyrings( + js_sys::JSON::parse(r#"{"store":"memory"}"#).expect("the options are JSON"), + ) + .await + .expect("memory lists"); + assert!(memory.is_empty()); +} + #[wasm_bindgen_test] async fn a_wrong_password_is_refused() { let name = unique_name("indexeddb"); From 222f6067c2ca94b1c3d3f192edcf7fd385ce2b27 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 17:33:43 -0500 Subject: [PATCH 12/18] Keep Turso keyrings out of each other's databases Turso's process-wide registry is keyed by the IO's file_id, so two IOs holding a same-named file resolved to one open database: a keyring opened from an image could read and write another keyring's secrets under the other's key. Give every IO an id of its own, and open a restored image under a fresh path instead of the one it recorded. The snapshot reader also trusted a file count from an unauthenticated header to size a map; a fifteen-byte input aborted the process. Refuse a count that is not the database and its WAL, and check the stored value is an image before converting it. --- src/keyring/opfs.rs | 13 ++++- src/keyring/turso.rs | 101 +++++++++++++++++++++++++++++++++++++++ src/keyring/turso_web.rs | 43 ++++++++++++++--- 3 files changed, 149 insertions(+), 8 deletions(-) diff --git a/src/keyring/opfs.rs b/src/keyring/opfs.rs index cb3a37f..3d869b4 100644 --- a/src/keyring/opfs.rs +++ b/src/keyring/opfs.rs @@ -180,6 +180,9 @@ impl PageStore for OpfsPages { /// obtained asynchronously: `open_file` itself cannot await. pub(crate) struct OpfsIo { files: HashMap>, + /// Distinguishes this IO in Turso's process-wide database registry, which + /// is keyed by `file_id`; see `WebIo::instance`. + instance: String, } impl OpfsIo { @@ -192,7 +195,10 @@ impl OpfsIo { let pages = OpfsPages::open(&path).await?; files.insert(path, Arc::new(OpfsFile::new(pages))); } - Ok(Self { files }) + Ok(Self { + files, + instance: super::turso_web::new_instance(), + }) } /// Flush both files to disk and release their handles. @@ -252,7 +258,10 @@ impl ::turso::core::IO for OpfsIo { } fn file_id(&self, path: &str) -> std::result::Result { - Ok(FileId::from_path_hash(path)) + Ok(FileId::from_path_hash(&format!( + "{}/{}", + self.instance, path + ))) } } diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index db67222..e5b7d90 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -270,6 +270,34 @@ mod tests { s.parse().unwrap() } + /// Rewrite a snapshot so its files sit under `base`, as two sessions do + /// when each names its first keyring the same thing. + fn with_paths(image: &[u8], base: &str) -> Vec { + let count = u32::from_le_bytes(image[11..15].try_into().unwrap()); + let mut rest = &image[15..]; + let mut out = image[..15].to_vec(); + for _ in 0..count { + let path_len = u32::from_le_bytes(rest[..4].try_into().unwrap()) as usize; + rest = &rest[4..]; + let path = std::str::from_utf8(&rest[..path_len]).unwrap(); + rest = &rest[path_len..]; + let data_len = u64::from_le_bytes(rest[..8].try_into().unwrap()) as usize; + let data = &rest[8..8 + data_len]; + rest = &rest[8 + data_len..]; + + let path = if path.ends_with("-wal") { + format!("{base}-wal") + } else { + base.to_string() + }; + out.extend_from_slice(&(path.len() as u32).to_le_bytes()); + out.extend_from_slice(path.as_bytes()); + out.extend_from_slice(&(data_len as u64).to_le_bytes()); + out.extend_from_slice(data); + } + out + } + #[test] fn cipher_param_parses() { assert_eq!(params("password=a").cipher, TursoCipher::Aegis256); @@ -335,6 +363,79 @@ mod tests { assert!(TursoKeyring::from_bytes(b"not a snapshot", &p).is_err()); } + #[test] + fn a_snapshot_claiming_huge_counts_is_refused() { + use crate::keyring::turso_web::WebIo; + + // Fifteen bytes used to size a HashMap from an unauthenticated count + // and abort the process on allocation failure. + let mut blob = b"CRYPTEX-IO".to_vec(); + blob.push(1); + blob.extend_from_slice(&u32::MAX.to_le_bytes()); + assert!(WebIo::restore(&blob).is_err()); + + // A count of two with no entries is malformed, not a panic. + let mut blob = b"CRYPTEX-IO".to_vec(); + blob.push(1); + blob.extend_from_slice(&2u32.to_le_bytes()); + assert!(WebIo::restore(&blob).is_err()); + } + + #[test] + fn two_ios_never_share_a_file_id() { + use crate::keyring::turso_web::WebIo; + use ::turso::core::IO; + + // Turso looks open databases up by `file_id`. Two IOs holding the same + // path - an OPFS keyring named `cryptex-1` and an in-memory image - must + // not resolve to one database, or one keyring writes into the other. + let a = WebIo::in_memory(); + let b = WebIo::in_memory(); + assert_ne!( + a.file_id("cryptex-1.db3").unwrap(), + b.file_id("cryptex-1.db3").unwrap() + ); + assert_eq!( + a.file_id("cryptex-1.db3").unwrap(), + a.file_id("cryptex-1.db3").unwrap() + ); + } + + #[test] + fn restored_images_do_not_reuse_the_recorded_path() { + // Turso keys its open databases by `file_id`, so two images recorded + // under one path used to share one open database: the second keyring + // read the first one's secrets and wrote into it. + let p = params("password=collide salt=1qaz2wsx3edc4rfv5tgb"); + + let mut first = TursoKeyring::in_memory(&p).unwrap(); + first.set_secret("first", b"one").unwrap(); + let image_a = first.export().unwrap(); + + let mut second = TursoKeyring::in_memory(&p).unwrap(); + second.set_secret("second", b"two").unwrap(); + let image_b = second.export().unwrap(); + + // Both images claim the same database path, as two page loads would + // when each named its first keyring the same thing. + let mut a = TursoKeyring::from_bytes(&with_paths(&image_a, "shared.db3"), &p).unwrap(); + let mut b = TursoKeyring::from_bytes(&with_paths(&image_b, "shared.db3"), &p).unwrap(); + + assert_eq!(a.get_secret("first").unwrap().0, b"one"); + assert_eq!(b.get_secret("second").unwrap().0, b"two"); + assert!(matches!( + b.get_secret("first"), + Err(KeyRingError::ItemNotFound) + )); + + // A write for one must not land in the other. + b.set_secret("later", b"kept").unwrap(); + assert!(matches!( + a.get_secret("later"), + Err(KeyRingError::ItemNotFound) + )); + } + #[test] fn copy_under_rekeys_without_touching_the_original() { let a = params("password=first salt=1qaz2wsx3edc4rfv5tgb"); diff --git a/src/keyring/turso_web.rs b/src/keyring/turso_web.rs index e11cde4..f284a77 100644 --- a/src/keyring/turso_web.rs +++ b/src/keyring/turso_web.rs @@ -37,6 +37,12 @@ const SNAPSHOT_VERSION: u8 = 1; /// Files held by [`WebIo`], keyed by the path Turso opened them with. pub(crate) struct WebIo { files: Mutex>>, + /// Distinguishes this IO in Turso's process-wide database registry. + /// + /// That registry is keyed by `file_id`, so two IOs holding a same-named + /// file would otherwise share one open database, including its encryption + /// key: one keyring would silently read and write the other's secrets. + instance: String, } impl WebIo { @@ -44,6 +50,7 @@ impl WebIo { pub(crate) fn in_memory() -> Arc { Arc::new(Self { files: Mutex::new(HashMap::new()), + instance: new_instance(), }) } @@ -95,8 +102,18 @@ impl WebIo { rest = &rest[1..]; let (count, tail) = take::<4>(rest).ok_or_else(malformed)?; rest = tail; - let mut files = HashMap::with_capacity(u32::from_le_bytes(count) as usize); - for _ in 0..u32::from_le_bytes(count) { + let count = u32::from_le_bytes(count); + // A database is the `.db3` file and the WAL beside it. A header + // claiming more is not a snapshot of ours, and sizing anything from it + // would let a fifteen-byte input ask for gigabytes. + if count > 2 { + return Err(malformed()); + } + // Open the image under a path of its own: the one in the image was + // chosen in another session, where the same path may still be open. + let base = unique_db_path(); + let mut files = HashMap::new(); + for _ in 0..count { let (len, tail) = take::<4>(rest).ok_or_else(malformed)?; rest = tail; let path_len = u32::from_le_bytes(len) as usize; @@ -114,10 +131,16 @@ impl WebIo { } let store = MemPages::from_vec(rest[..data_len].to_vec()); rest = &rest[data_len..]; + let path = if path.ends_with("-wal") { + format!("{base}-wal") + } else { + base.clone() + }; files.insert(path, Arc::new(WebFile::new(store))); } Ok(Arc::new(Self { files: Mutex::new(files), + instance: new_instance(), })) } @@ -127,9 +150,6 @@ impl WebIo { } /// A database path no other in-memory keyring uses. -/// -/// Turso keys its open databases by path, so two in-memory keyrings that -/// shared one would share a page cache and an encryption key. pub(crate) fn unique_db_path() -> String { use std::sync::atomic::{AtomicU64, Ordering}; @@ -137,6 +157,14 @@ pub(crate) fn unique_db_path() -> String { format!("cryptex-{}.db3", NEXT.fetch_add(1, Ordering::Relaxed)) } +/// An IO id no other IO in this process has. +pub(super) fn new_instance() -> String { + use std::sync::atomic::{AtomicU64, Ordering}; + + static NEXT: AtomicU64 = AtomicU64::new(1); + format!("io-{}", NEXT.fetch_add(1, Ordering::Relaxed)) +} + fn poisoned() -> KeyRingError { KeyRingError::GeneralError { msg: "the in-memory database lock is poisoned".to_string(), @@ -187,7 +215,10 @@ impl IO for WebIo { } fn file_id(&self, path: &str) -> TursoResult { - Ok(FileId::from_path_hash(path)) + Ok(FileId::from_path_hash(&format!( + "{}/{}", + self.instance, path + ))) } fn is_memory(&self) -> bool { From 0a41d4c89bb12c3d9e36ebd7e184031c61d84462 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 17:33:45 -0500 Subject: [PATCH 13/18] Bound what an image can ask for, and close the browser gaps An imported blob carried its Argon2 costs in an unauthenticated header, so a crafted image could demand terabytes and minutes of work before the AEAD noticed. Bound them before deriving, and check the salt length with checked arithmetic: on wasm32 the old check wrapped and a debug build panicked slicing the blob. On the browser side, a closed keyring now refuses every call instead of silently accepting writes that go nowhere, a localStorage keyring takes the same single-opener Web Lock as IndexedDB, an aborted transaction rejects instead of hanging, and a repeated connection-string keyword is an error rather than a silent override. Secret buffers and the AEAD key schedules are zeroized. --- Cargo.toml | 4 +- examples/web/worker.js | 5 ++ src/keyring/file_common.rs | 17 +++++- src/keyring/indexeddb.rs | 25 +++++++-- src/keyring/memory.rs | 112 +++++++++++++++++++++++++++++++++---- src/keyring/web_storage.rs | 5 ++ src/wasm.rs | 69 ++++++++++++++--------- tests/wasm.rs | 40 +++++++++++++ 8 files changed, 233 insertions(+), 44 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 28c3697..c17a151 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -81,9 +81,9 @@ yubihsm-usb = ["dep:yubihsm", "yubihsm/usb", "yubihsm/passwords", "dep:aes-gcm", yubihsm-http = ["dep:yubihsm", "yubihsm/http", "yubihsm/passwords", "dep:aes-gcm", "dep:sha2", "dep:getrandom", "dep:dirs"] [dependencies] -aes-gcm = { version = "0.11", optional = true } +aes-gcm = { version = "0.11", features = ["zeroize"], optional = true } argon2 = { version = "0.5", optional = true } -chacha20poly1305 = { version = "0.11", optional = true } +chacha20poly1305 = { version = "0.11", features = ["zeroize"], optional = true } clap = "4.6.1" colored = "3.0" dirs = { version = "6.0", optional = true } diff --git a/examples/web/worker.js b/examples/web/worker.js index df54d2f..90d83ab 100644 --- a/examples/web/worker.js +++ b/examples/web/worker.js @@ -17,6 +17,11 @@ let ready = null; let keyring = null; async function open({ password, name }) { + // The connection string is whitespace-separated, so a password that holds a + // space, or a ` salt=` of its own, would change how it is parsed. + if (!password || /\s/.test(password)) { + throw new Error("the password must be non-empty and cannot contain spaces"); + } ready ??= init(); await ready; if (keyring) await keyring.close(); diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 3da30aa..52a9ac9 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -500,8 +500,11 @@ pub(crate) fn acquire_single_opener_lock(db_path: &Path) -> Result { Err(TryLockError::WouldBlock) => Err(KeyRingError::AccessDenied { msg: "keyring is already open by another process".to_string(), }), - // WASI and some network filesystems do not implement locking; a - // keyring there relies on the caller keeping a single writer. + // WASI does not implement locking at all, so a keyring there relies on + // the caller keeping a single writer. Everywhere else a filesystem + // that refuses to lock is an error: FUSE, NFS and SMB mounts report + // `Unsupported`, and opening unlocked would let two writers race. + #[cfg(target_os = "wasi")] Err(TryLockError::Error(e)) if e.kind() == std::io::ErrorKind::Unsupported => Ok(file), Err(TryLockError::Error(e)) => Err(KeyRingError::GeneralError { msg: format!("unable to lock keyring: {}", e), @@ -627,8 +630,18 @@ impl<'a> Parser<'a> { }; let mut connection_string = ConnectionParams::default(); + // A repeated keyword used to overwrite the first one, so a password + // that contained ` salt=...` could silently swap the salt or turn the + // password into a raw key. + let mut seen: Vec<&'a str> = Vec::new(); while let Some((key, value)) = parser.parameter()? { + if seen.contains(&key) { + return Err(KeyRingError::GeneralError { + msg: format!("duplicate parameter: {}", key), + }); + } + seen.push(key); connection_string.param(key, &value)?; } Ok(connection_string) diff --git a/src/keyring/indexeddb.rs b/src/keyring/indexeddb.rs index 416cf1e..bcf3563 100644 --- a/src/keyring/indexeddb.rs +++ b/src/keyring/indexeddb.rs @@ -87,8 +87,14 @@ impl SnapshotStore { drop(tx); if value.is_undefined() || value.is_null() { Ok(None) - } else { + } else if value.is_instance_of::() { Ok(Some(js_sys::Uint8Array::new(&value).to_vec())) + } else { + // `Uint8Array::new` would allocate whatever length the stored + // value claims; refuse anything that is not already an image. + Err(KeyRingError::AccessDenied { + msg: "the stored keyring is not an image".to_string(), + }) } } @@ -141,7 +147,7 @@ impl SnapshotStore { /// /// The lock lives as long as the promise the callback returns, so dropping /// this resolves that promise and lets the next tab in. -struct LockHold { +pub(crate) struct LockHold { /// Resolves the promise the lock callback returned. release: std::rc::Rc>>, /// The promise itself: the lock is held until it settles. @@ -153,7 +159,7 @@ struct LockHold { } impl LockHold { - async fn acquire(name: &str) -> Result { + pub(crate) async fn acquire(name: &str) -> Result { let locks = Reflect::get(&navigator()?, &JsValue::from_str("locks")).map_err(js_error)?; if locks.is_undefined() || locks.is_null() { return Err(unsupported( @@ -238,7 +244,7 @@ impl LockHold { impl LockHold { /// Release the lock and wait for the browser to finish doing so. - async fn release_async(&mut self) { + pub(crate) async fn release_async(&mut self) { if let Some(release) = self.release.borrow_mut().take() { let _ = release.call0(&JsValue::NULL); } @@ -343,8 +349,19 @@ async fn await_transaction(tx: &IdbTransaction) -> Result<()> { let _ = reject.call1(&JsValue::NULL, &err); }) }; + // A quota or abort failure fires neither event reliably in every + // browser, and an unsettled promise would make `set` hang forever. + let on_abort = { + let tx = tx.clone(); + let reject = reject.clone(); + Closure::::once_into_js(move |_event: JsValue| { + let err = tx.error().map(JsValue::from).unwrap_or(JsValue::NULL); + let _ = reject.call1(&JsValue::NULL, &err); + }) + }; tx.set_oncomplete(Some(on_complete.unchecked_ref())); tx.set_onerror(Some(on_error.unchecked_ref())); + tx.set_onabort(Some(on_abort.unchecked_ref())); }); JsFuture::from(promise).await.map(|_| ()).map_err(js_error) } diff --git a/src/keyring/memory.rs b/src/keyring/memory.rs index 0b5a25c..e3cac97 100644 --- a/src/keyring/memory.rs +++ b/src/keyring/memory.rs @@ -55,6 +55,15 @@ const BLOB_VERSION: u8 = 1; const HEADER_LEN: usize = 8 + 1 + 1 + 1 + 4 + 4 + 4 + 4; const NONCE_SIZE: usize = 12; +/// Highest Argon2 costs an imported blob may ask for. +/// +/// The costs sit in an unauthenticated header, so they are checked before +/// Argon2 runs: a crafted sixteen-byte blob would otherwise ask for terabytes +/// and minutes of work before the AEAD notices it is not authentic. +const MAX_IMPORT_MEMORY_KIB: u32 = 1024 * 1024; +const MAX_IMPORT_THREADS: u32 = 64; +const MAX_IMPORT_PARALLEL: u32 = 64; + /// How the blob's key was produced. mod kind { /// Argon2id over password + salt. @@ -136,14 +145,24 @@ impl Sealer { /// Length-prefixed encoding of the secret table: /// `count(u32) | [id_len(u32) id value_len(u32) value]*`. -fn encode_secrets(secrets: &BTreeMap>>) -> Result> { +fn encode_secrets(secrets: &BTreeMap>>) -> Result>> { let too_long = |what: &str| KeyRingError::GeneralError { msg: format!("{} is too large to export", what), }; - let mut out = u32::try_from(secrets.len()) - .map_err(|_| too_long("the secret count"))? - .to_le_bytes() - .to_vec(); + // Size the buffer up front: a growing buffer copies the plaintext into + // freed allocations, which zeroizing afterwards cannot reach. + let mut len: usize = 4; + for (id, value) in secrets { + len = len + .checked_add(4 + id.len() + 4 + value.len()) + .ok_or_else(|| too_long("the secret table"))?; + } + let mut out = Zeroizing::new(Vec::with_capacity(len)); + out.extend_from_slice( + &u32::try_from(secrets.len()) + .map_err(|_| too_long("the secret count"))? + .to_le_bytes(), + ); for (id, value) in secrets { let id_len = u32::try_from(id.len()).map_err(|_| too_long("a secret id"))?; let value_len = u32::try_from(value.len()).map_err(|_| too_long("a secret value"))?; @@ -238,6 +257,14 @@ impl MemoryKeyring { /// [`KeyRingError::AccessDenied`]. pub fn import(blob: &[u8], password_or_key: &[u8]) -> Result { let header = Self::parse_header(blob)?; + if header.memory > MAX_IMPORT_MEMORY_KIB + || header.threads > MAX_IMPORT_THREADS + || header.parallel > MAX_IMPORT_PARALLEL + { + return Err(KeyRingError::GeneralError { + msg: "the keyring blob asks for unreasonable Argon2 costs".to_string(), + }); + } let params = ConnectionParams { key: if header.kind == kind::RAW_KEY { password_or_key.to_vec() @@ -298,11 +325,15 @@ impl MemoryKeyring { let threads = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; let parallel = read_u32(blob, &mut pos).ok_or_else(invalid_blob)?; let salt_len = read_u32(blob, &mut pos).ok_or_else(invalid_blob)? as usize; - let salt = blob - .get(HEADER_LEN..HEADER_LEN + salt_len) - .ok_or_else(invalid_blob)?; + // `usize` is 32 bits on wasm32, so this addition can wrap before a + // bounds check would notice. + let salt_end = HEADER_LEN.checked_add(salt_len).ok_or_else(invalid_blob)?; + let salt = blob.get(HEADER_LEN..salt_end).ok_or_else(invalid_blob)?; // The body must hold a nonce and at least the AEAD tag. - if salt_len.checked_add(HEADER_LEN + NONCE_SIZE + 16) > Some(blob.len()) { + let body_start = salt_end + .checked_add(NONCE_SIZE + 16) + .ok_or_else(invalid_blob)?; + if body_start > blob.len() { return Err(invalid_blob()); } Ok(Header { @@ -325,7 +356,7 @@ impl MemoryKeyring { msg: format!("unable to generate a nonce: {}", e), })?; - let plaintext = Zeroizing::new(encode_secrets(&self.secrets)?); + let plaintext = encode_secrets(&self.secrets)?; let salt_len = u32::try_from(self.salt.len()).map_err(|_| KeyRingError::GeneralError { msg: "salt is too long to export".to_string(), })?; @@ -420,6 +451,7 @@ mod tests { use super::super::DynKeyRing; use super::{CipherAlgorithm, ConnectionParams, HEADER_LEN, MemoryKeyring}; use crate::error::KeyRingError; + use argon2::Params as Argon2Params; const PASSWORD: &[u8] = b"1qaz2wsx3edc4rfv"; @@ -485,6 +517,66 @@ mod tests { )); } + /// A blob header with whatever Argon2 costs a hostile image would ask for. + fn blob_with_costs(memory: u32, threads: u32, parallel: u32, salt_len: u32) -> Vec { + let mut blob = Vec::new(); + blob.extend_from_slice(b"CRYPTEX\0"); + blob.push(1); // version + blob.push(super::kind::PASSWORD); + blob.push(super::seal_cipher(CipherAlgorithm::default())); + blob.extend_from_slice(&memory.to_le_bytes()); + blob.extend_from_slice(&threads.to_le_bytes()); + blob.extend_from_slice(¶llel.to_le_bytes()); + blob.extend_from_slice(&salt_len.to_le_bytes()); + blob.extend_from_slice(b"saltsalt"); + blob.extend_from_slice(&[0u8; super::NONCE_SIZE + 16]); + blob + } + + #[test] + fn import_refuses_unreasonable_costs_before_deriving() { + // These sit in an unauthenticated header, so they must be bounded + // before Argon2 tries to honour them. + for (memory, threads, parallel) in [ + (u32::MAX, 1, 1), + (Argon2Params::DEFAULT_M_COST, u32::MAX, 1), + (Argon2Params::DEFAULT_M_COST, 1, u32::MAX), + ] { + let blob = blob_with_costs(memory, threads, parallel, 8); + assert!(matches!( + MemoryKeyring::import(&blob, PASSWORD), + Err(KeyRingError::GeneralError { .. }) + )); + } + } + + #[test] + fn import_refuses_a_salt_length_that_would_overflow() { + // `usize` is 32 bits on wasm32, where the old bounds check wrapped and + // a debug build then panicked slicing the blob. + let blob = blob_with_costs( + Argon2Params::DEFAULT_M_COST, + Argon2Params::DEFAULT_T_COST, + Argon2Params::DEFAULT_P_COST, + u32::MAX, + ); + assert!(matches!( + MemoryKeyring::import(&blob, PASSWORD), + Err(KeyRingError::AccessDenied { .. }) + )); + } + + #[test] + fn a_duplicate_parameter_is_refused() { + // A password containing ` salt=` used to silently replace the salt. + assert!( + "password=a salt=b salt=c" + .parse::() + .is_err() + ); + assert!("password=a password=b".parse::().is_err()); + } + #[test] fn tampering_is_detected() { let mut kr = MemoryKeyring::with_params(&password_params("")).unwrap(); diff --git a/src/keyring/web_storage.rs b/src/keyring/web_storage.rs index f279d31..2f436f8 100644 --- a/src/keyring/web_storage.rs +++ b/src/keyring/web_storage.rs @@ -28,6 +28,11 @@ //! under storage pressure unless the site has been granted persistent storage //! ([`request_persistent_storage`]). The image is encrypted, so what a script //! gets is ciphertext. +//! +//! There is no cross-tab lock here: the whole image is rewritten on every +//! change, so two tabs on one name would lose each other's secrets. Take the +//! `cryptex:` Web Lock first, as the JavaScript `Keyring` does, or give +//! each tab its own name. use super::cipher::CipherAlgorithm; use super::file_common; diff --git a/src/wasm.rs b/src/wasm.rs index 5a98560..e042837 100644 --- a/src/wasm.rs +++ b/src/wasm.rs @@ -49,6 +49,7 @@ use zeroize::Zeroizing; use crate::DynKeyRing; use crate::error::KeyRingError; +use crate::indexeddb::LockHold; use crate::indexeddb::SnapshotStore; use crate::memory::MemoryKeyring; use crate::turso::TursoKeyring; @@ -70,7 +71,8 @@ enum Inner { dirty: bool, }, Memory { - keyring: MemoryKeyring, + /// `None` once the keyring is closed. + keyring: Option, store: Store, dirty: bool, }, @@ -82,7 +84,9 @@ enum Store { /// The database is an OPFS file; it holds its own data. Opfs, IndexedDb(SnapshotStore), - LocalStorage(LocalStorageImage), + /// An image in `localStorage`, with the lock that keeps two tabs from + /// overwriting each other's image. + LocalStorage(LocalStorageImage, LockHold), } #[wasm_bindgen] @@ -127,11 +131,11 @@ impl Keyring { }) } Backend::Memory => { - let keyring = - MemoryKeyring::import(image, &memory_secret(connection)?).map_err(js)?; + let keyring = MemoryKeyring::import(image, memory_secret(connection)?.as_slice()) + .map_err(js)?; Ok(Keyring { inner: Inner::Memory { - keyring, + keyring: Some(keyring), store: Store::None, dirty: false, }, @@ -144,7 +148,7 @@ impl Keyring { pub fn get(&mut self, id: &str) -> Result, JsError> { let secret = match &mut self.inner { Inner::Turso { keyring, .. } => keyring.as_mut().ok_or_else(closed)?.get_secret(id), - Inner::Memory { keyring, .. } => keyring.get_secret(id), + Inner::Memory { keyring, .. } => keyring.as_mut().ok_or_else(closed)?.get_secret(id), } .map_err(js)?; let value: Zeroizing> = Zeroizing::new(secret.0.clone()); @@ -172,9 +176,9 @@ impl Keyring { store, dirty, } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.set_secret(id, secret).map_err(js)?; *dirty = true; - let keyring = &*keyring; flush(store, dirty, || keyring.export()).await } } @@ -198,9 +202,9 @@ impl Keyring { store, dirty, } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.delete_secret(id).map_err(js)?; *dirty = true; - let keyring = &*keyring; flush(store, dirty, || keyring.export()).await } } @@ -238,9 +242,9 @@ impl Keyring { store, dirty, } => { + let keyring = keyring.as_mut().ok_or_else(closed)?; keyring.rekey(&memory_params(connection)?).map_err(js)?; *dirty = true; - let keyring = &*keyring; flush(store, dirty, || keyring.export()).await } } @@ -250,7 +254,7 @@ impl Keyring { pub fn keys(&self) -> Result, JsError> { match &self.inner { Inner::Turso { keyring, .. } => keyring.as_ref().ok_or_else(closed)?.keys().map_err(js), - Inner::Memory { keyring, .. } => Ok(keyring.keys()), + Inner::Memory { keyring, .. } => Ok(keyring.as_ref().ok_or_else(closed)?.keys()), } } @@ -260,15 +264,17 @@ impl Keyring { Inner::Turso { keyring, .. } => { keyring.as_ref().ok_or_else(closed)?.export().map_err(js) } - Inner::Memory { keyring, .. } => keyring.export().map_err(js), + Inner::Memory { keyring, .. } => { + keyring.as_ref().ok_or_else(closed)?.export().map_err(js) + } } } /// Flush any pending change and release the store. /// /// A keyring holding a Web Lock releases it here, letting another tab - /// open the same name. The keyring still answers reads and writes, but it - /// no longer has anywhere to persist them. + /// open the same name. Every other method then throws, so a caller cannot + /// keep writing to a keyring whose changes have nowhere to go. pub async fn close(&mut self) -> Result<(), JsError> { match &mut self.inner { Inner::Turso { @@ -287,8 +293,10 @@ impl Keyring { store, dirty, } => { - // The secrets stay readable; they just have nowhere to go. - flush(store, dirty, || keyring.export()).await?; + if let Some(keyring) = keyring.as_ref() { + flush(store, dirty, || keyring.export()).await?; + } + *keyring = None; release(store).await; } } @@ -334,12 +342,15 @@ async fn open_turso(connection: &str, name: &str, store: StoreKind) -> Result { + let hold = LockHold::acquire(&format!("cryptex:{name}")) + .await + .map_err(js)?; let image = LocalStorageImage::new(Some(name))?; let keyring = match image.load()? { Some(bytes) => TursoKeyring::from_bytes(&bytes, ¶ms).map_err(js)?, None => TursoKeyring::in_memory(¶ms).map_err(js)?, }; - (keyring, Store::LocalStorage(image)) + (keyring, Store::LocalStorage(image, hold)) } StoreKind::Opfs => { let keyring = TursoKeyring::open_opfs(¶ms, name).await.map_err(js)?; @@ -363,18 +374,21 @@ async fn open_memory(connection: &str, name: &str, store: StoreKind) -> Result { let snapshot = SnapshotStore::open(name).await.map_err(js)?; let keyring = match snapshot.load().await.map_err(js)? { - Some(image) => MemoryKeyring::import(&image, &secret).map_err(js)?, + Some(image) => MemoryKeyring::import(&image, secret.as_slice()).map_err(js)?, None => MemoryKeyring::with_params(¶ms).map_err(js)?, }; (keyring, Store::IndexedDb(snapshot)) } StoreKind::LocalStorage => { + let hold = LockHold::acquire(&format!("cryptex:{name}")) + .await + .map_err(js)?; let image = LocalStorageImage::new(Some(name))?; let keyring = match image.load()? { - Some(bytes) => MemoryKeyring::import(&bytes, &secret).map_err(js)?, + Some(bytes) => MemoryKeyring::import(&bytes, secret.as_slice()).map_err(js)?, None => MemoryKeyring::with_params(¶ms).map_err(js)?, }; - (keyring, Store::LocalStorage(image)) + (keyring, Store::LocalStorage(image, hold)) } StoreKind::Memory => ( MemoryKeyring::with_params(¶ms).map_err(js)?, @@ -389,7 +403,7 @@ async fn open_memory(connection: &str, name: &str, store: StoreKind) -> Result Result snapshot.release().await, + Store::LocalStorage(_, hold) => hold.release_async().await, + Store::None | Store::Opfs => {} } *store = Store::None; } @@ -419,7 +435,7 @@ async fn flush( match store { Store::None | Store::Opfs => {} Store::IndexedDb(snapshot) => snapshot.save(&image().map_err(js)?).await.map_err(js)?, - Store::LocalStorage(local) => local.save(&image().map_err(js)?)?, + Store::LocalStorage(local, _) => local.save(&image().map_err(js)?)?, } *dirty = false; Ok(()) @@ -506,13 +522,14 @@ fn memory_params(connection: &str) -> Result Result, JsError> { +/// The password or raw key, wrapped so its copy is wiped on the way out. +fn memory_secret(connection: &str) -> Result>, JsError> { let params = memory_params(connection)?; - Ok(if params.key.is_empty() { + Ok(Zeroizing::new(if params.key.is_empty() { params.password.clone() } else { params.key.clone() - }) + })) } fn closed() -> JsError { diff --git a/tests/wasm.rs b/tests/wasm.rs index 891095b..6832545 100644 --- a/tests/wasm.rs +++ b/tests/wasm.rs @@ -38,6 +38,46 @@ async fn memory_keyring_round_trips() { keyring.close().await.expect("close succeeds"); } +#[wasm_bindgen_test] +async fn a_closed_keyring_refuses_every_call() { + let mut keyring = Keyring::open(CONNECTION, &unique_name("closed"), Default::default()) + .await + .expect("a memory keyring opens"); + keyring.set("token", b"secret").await.expect("set succeeds"); + keyring.close().await.expect("close succeeds"); + + let error = keyring + .set("token", b"other") + .await + .expect_err("a closed keyring refuses writes"); + assert!(format!("{error:?}").contains("closed"), "{error:?}"); + assert!(keyring.get("token").is_err()); + assert!(keyring.delete("token").await.is_err()); + assert!(keyring.keys().is_err()); +} + +#[wasm_bindgen_test] +async fn local_storage_takes_one_opener() { + // Two tabs rewriting one image would lose each other's secrets, so the + // second opener is refused instead. + let name = unique_name("locked"); + let options = + || js_sys::JSON::parse(r#"{"store":"localstorage"}"#).expect("the options are JSON"); + + let mut first = Keyring::open(CONNECTION, &name, options()) + .await + .expect("the first opener gets the keyring"); + let second = Keyring::open(CONNECTION, &name, options()).await; + assert!(second.is_err(), "a second opener must be refused"); + + // Closing releases the lock, so the name can be opened again. + first.close().await.expect("close succeeds"); + let mut reopened = Keyring::open(CONNECTION, &name, options()) + .await + .expect("closing releases the lock"); + reopened.close().await.expect("close succeeds"); +} + #[wasm_bindgen_test] async fn indexeddb_keeps_the_secrets() { let name = unique_name("indexeddb"); From 61c8a57720eb398291843a56d509c1454ef5bde7 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 17:33:48 -0500 Subject: [PATCH 14/18] Keep the HSM backends in CI, and write down the limits The explicit feature lists replaced --all-features, which quietly stopped linting, testing and documenting the YubiHSM backends; list them too. Give the workflow a read-only token and build wasm-pack from a pinned version instead of piping an unpinned installer into a shell. The README now says what the encryption does not cover: a stale image is not detected, and the connection string is a small DSL, so a password with whitespace or quotes in it is not passed through unchanged. --- .github/workflows/cryptex.yml | 13 +++++++++---- README.md | 27 ++++++++++++++++++++++----- 2 files changed, 31 insertions(+), 9 deletions(-) diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index 7ef02a4..b6bed6b 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -1,5 +1,8 @@ name: Cryptex CI +permissions: + contents: read + on: push: branches: main @@ -46,7 +49,7 @@ jobs: - name: Install native dependencies for encrypted-vfs and YubiHSM run: sudo apt-get install -y libclang-dev libusb-1.0-0-dev - run: cargo clippy --no-default-features --features encrypted-vfs -- -D warnings - - run: cargo clippy --all-targets --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io" -- -D warnings + - run: cargo clippy --all-targets --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io,yubihsm-usb,yubihsm-http" -- -D warnings clippy-macos: runs-on: macos-latest @@ -104,7 +107,9 @@ jobs: cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" - name: Install wasm-pack - run: curl https://rustwasm.github.io/wasm-pack/installer/init.sh -sSf | sh + # Pinned and built from the registry: piping an unpinned installer + # script into a shell runs whatever that URL serves today. + run: cargo install wasm-pack --locked --version 0.13.1 - name: Build the JavaScript package run: wasm-pack build --target web --no-default-features --features js - name: Set up Chrome and ChromeDriver @@ -155,7 +160,7 @@ jobs: - name: Install native dependencies for encrypted-vfs and YubiHSM run: sudo apt-get install -y libclang-dev libusb-1.0-0-dev - run: cargo doc --no-default-features --features encrypted-vfs - - run: cargo doc --no-deps --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io" + - run: cargo doc --no-deps --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io,yubihsm-usb,yubihsm-http" doc-macos: runs-on: macos-latest @@ -223,7 +228,7 @@ jobs: run: cargo test --test default_argon2_params --no-default-features --features "file,encrypted-vfs" - name: Test all features if: matrix.cache-key == 'encrypted-vfs' - run: cargo test --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io" + run: cargo test --features "file,serde,encrypted-vfs,memory,turso,turso-encrypted-io,yubihsm-usb,yubihsm-http" macos: runs-on: macos-latest diff --git a/README.md b/README.md index e055d26..e68dd09 100644 --- a/README.md +++ b/README.md @@ -203,11 +203,14 @@ Every store keeps the data encrypted; the key comes from the password (or raw key) in the connection string, so a store with the wrong connection string fails with `AccessDenied` instead of returning garbage. -A `set` or `delete` that resolves has reached the store. An IndexedDB keyring -also holds a Web Lock named after itself, so a second tab that opens the same -name fails with `AccessDenied` instead of overwriting the first tab's secrets; -`close()` releases the lock, and with OPFS the sync access handle, so close a -keyring before opening it again in the same context. +A `set` or `delete` that resolves has reached the store, and every call on a +closed keyring throws. An IndexedDB or localStorage keyring also holds a Web +Lock named after itself, so a second tab that opens the same name fails with +`AccessDenied` instead of overwriting the first tab's secrets; `close()` +releases the lock, and with OPFS the sync access handle, so close a keyring +before opening it again in the same context. The Rust-level +`WebStorageKeyring` does not take that lock: it is synchronous by design, and +taking a lock is not. OPFS needs `createSyncAccessHandle()`, which browsers expose only in a dedicated worker, so `store: "opfs"` is refused on the main thread. A worker @@ -227,6 +230,20 @@ refuse, and clearing site data always removes it. Key derivation runs Argon2, which blocks the thread it runs on: with a large `memory=` value, open the keyring in a worker or the page freezes until it finishes. +What the encryption does not detect is a *stale* image. Code that can write +origin storage can put back an earlier one, or drop the `-wal` beside it, and +the keyring opens with the secrets it held then; a rotated secret can come +back that way. Keep a version or counter of your own outside the store if that +matters. + +The password reaches the library through the connection string, which is a +small DSL: `\` starts an escape, a leading `'` quotes a value, and whitespace +separates entries. A password containing those characters is not passed +through unchanged, so derive a key yourself or hex-encode the secret when the +password is user-supplied. A repeated keyword (`password=a password=b`) is an +error rather than a silent override. The examples use one fixed salt to stay +readable; an application should give each keyring a salt of its own. + ### Bringing your own storage `TursoKeyring` can adopt a connection you opened, or open through an IO you From cdecc133f5f52d26dd30a210cd50f809bc11a6e8 Mon Sep 17 00:00:00 2001 From: Doug Cooper Date: Fri, 20 Nov 2026 17:53:34 -0500 Subject: [PATCH 15/18] Give a Turso keyring one backing, and name OPFS after Turso TursoKeyring carried the store and an Option> that was Some exactly when cryptex made the database itself. Two fields, one meaning: export and copy_under branched on the flag, each constructor patched it afterwards, and on a native build the field was always None. Make it one enum: Stored holds a file or a caller's connection, InMemory holds the database cryptex made plus the IO that can copy it out. export is now a match arm rather than a runtime check, and the two modes cannot drift. Also rename the opfs feature to turso-opfs. It is a Turso IO, not a store that layers over export(), so it belongs beside turso-encrypted-io rather than beside indexeddb and web-storage. The JS store name is unchanged. --- .github/workflows/cryptex.yml | 2 +- Cargo.toml | 4 +- README.md | 2 +- src/error.rs | 4 +- src/keyring.rs | 14 +++-- src/keyring/file_common.rs | 1 - src/keyring/turso.rs | 113 +++++++++++++++++++++++++--------- 7 files changed, 99 insertions(+), 41 deletions(-) diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index b6bed6b..c1b8528 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -103,7 +103,7 @@ jobs: cargo clippy --target wasm32-unknown-unknown --no-default-features --features turso -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-encrypted-io" -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features memory -- -D warnings - cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,opfs,indexeddb,web-storage,js" -- -D warnings + cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-opfs,indexeddb,web-storage,js" -- -D warnings cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" - name: Install wasm-pack diff --git a/Cargo.toml b/Cargo.toml index c17a151..a8c54c5 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -52,7 +52,7 @@ web-storage = [ "dep:js-sys", ] indexeddb = ["memory", "dep:web-sys", "dep:wasm-bindgen", "dep:wasm-bindgen-futures", "dep:js-sys"] -opfs = [ +turso-opfs = [ "turso", "dep:web-sys", "dep:wasm-bindgen", @@ -63,7 +63,7 @@ js = [ "memory", "web-storage", "indexeddb", - "opfs", + "turso-opfs", "turso", "dep:web-sys", "dep:wasm-bindgen", diff --git a/README.md b/README.md index e68dd09..cc989b3 100644 --- a/README.md +++ b/README.md @@ -139,7 +139,7 @@ open. `rekey` re-derives the key without touching the secrets. | `turso-encrypted-io` | builds | yes | the page cipher needs a `PageStore`; the file-backed one is native only | | `web-storage` | yes | no | a `MemoryKeyring` sealed into `localStorage` | | `indexeddb` | yes | no | encrypted image snapshots, one per keyring | -| `opfs` | yes | no | the database file itself in the origin private file system | +| `turso-opfs` | yes | no | the database file itself in the origin private file system | | `js` | yes | no | the `wasm-bindgen` `Keyring` class | | `file`, `encrypted-vfs` | no | no | SQLCipher and the bundled C VFS are native only | | OS keyrings, `yubihsm-*` | no | no | no OS keychain or USB device | diff --git a/src/error.rs b/src/error.rs index 50180bd..dddd4bc 100644 --- a/src/error.rs +++ b/src/error.rs @@ -124,10 +124,10 @@ impl From for KeyRingError { } /// Browser APIs report failures as thrown JavaScript values. -#[cfg(any(feature = "indexeddb", feature = "opfs", feature = "web-storage"))] +#[cfg(any(feature = "indexeddb", feature = "turso-opfs", feature = "web-storage"))] #[cfg_attr( docsrs, - doc(cfg(any(feature = "indexeddb", feature = "opfs", feature = "web-storage"))) + doc(cfg(any(feature = "indexeddb", feature = "turso-opfs", feature = "web-storage"))) )] impl From for KeyRingError { fn from(value: wasm_bindgen::JsValue) -> Self { diff --git a/src/keyring.rs b/src/keyring.rs index 0cb150a..7ba529e 100644 --- a/src/keyring.rs +++ b/src/keyring.rs @@ -32,7 +32,7 @@ pub mod linux; pub mod macos; #[cfg(feature = "memory")] pub mod memory; -#[cfg(feature = "opfs")] +#[cfg(feature = "turso-opfs")] pub mod opfs; #[cfg(any(feature = "encrypted-vfs", feature = "turso-encrypted-io"))] mod page_cipher; @@ -40,7 +40,7 @@ mod page_cipher; feature = "encrypted-vfs", feature = "turso", feature = "turso-encrypted-io", - feature = "opfs" + feature = "turso-opfs" ))] mod page_store; #[cfg(feature = "file")] @@ -57,7 +57,7 @@ pub mod turso_encrypted_io; mod turso_web; #[cfg(feature = "web-storage")] pub mod web_storage; -#[cfg(any(feature = "opfs", feature = "turso"))] +#[cfg(any(feature = "turso-opfs", feature = "turso"))] mod web_time; #[cfg(all(target_os = "windows", feature = "windows-credentials"))] pub mod windows; @@ -151,7 +151,7 @@ compile_error!("no keyring implementation is selected or available for this plat ))] compile_error!( "the file, encrypted-vfs, yubihsm and OS keyring backends are not available on wasm; \ - use the memory, web-storage, indexeddb, opfs or turso features instead" + use the memory, web-storage, indexeddb, turso-opfs or turso features instead" ); // Browser-only features asked for by a non-browser target. @@ -160,11 +160,13 @@ compile_error!( any( feature = "web-storage", feature = "indexeddb", - feature = "opfs", + feature = "turso-opfs", feature = "js" ) ))] -compile_error!("the web-storage, indexeddb, opfs and js features require wasm32-unknown-unknown"); +compile_error!( + "the web-storage, indexeddb, turso-opfs and js features require wasm32-unknown-unknown" +); #[cfg(any( all(target_os = "linux", feature = "linux-secret-service"), diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 52a9ac9..2cb9002 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -152,7 +152,6 @@ macro_rules! file_keyring { #[cfg(any( feature = "file", feature = "encrypted-vfs", - feature = "turso", feature = "turso-encrypted-io", feature = "yubihsm-usb", feature = "yubihsm-http" diff --git a/src/keyring/turso.rs b/src/keyring/turso.rs index e5b7d90..9e3daaa 100644 --- a/src/keyring/turso.rs +++ b/src/keyring/turso.rs @@ -14,8 +14,8 @@ use std::path::PathBuf; use std::sync::Arc; use zeroize::{Zeroize, Zeroizing}; -use super::file_common::{self, CipherParam, derive_key_32, file_keyring, secure_file}; -#[cfg(feature = "opfs")] +use super::file_common::{self, CipherParam, derive_key_32, secure_file}; +#[cfg(feature = "turso-opfs")] use super::opfs::OpfsIo; use super::turso_common::TursoFile; use super::turso_web::{WebIo, unique_db_path}; @@ -90,21 +90,66 @@ pub use ::turso::core; /// - [`with_io`](Self::with_io) opens through a caller-supplied Turso `IO`, /// such as the Origin Private File System in a browser worker. pub struct TursoKeyring { - file: TursoFile, - /// Set on keyrings whose database lives in memory, so it can be copied out. - web: Option>, + backing: Backing, } -file_keyring!(TursoKeyring, file); +/// Where a keyring's database lives. +enum Backing { + /// A file, or a connection the caller owns, that outlives the keyring. + Stored(TursoFile), + /// A database cryptex made in memory, so it can be copied out as an image. + InMemory { file: TursoFile, io: Arc }, +} + +impl Backing { + fn file(&self) -> &TursoFile { + match self { + Self::Stored(file) | Self::InMemory { file, .. } => file, + } + } + + fn into_file(self) -> TursoFile { + match self { + Self::Stored(file) | Self::InMemory { file, .. } => file, + } + } +} + +impl DynKeyRing for TursoKeyring { + fn get_secret(&mut self, id: &str) -> Result { + file_common::SecretStore::get(self.file(), id) + } + + fn set_secret(&mut self, id: &str, secret: &[u8]) -> Result<()> { + file_common::SecretStore::set(self.file(), id, secret) + } + + fn delete_secret(&mut self, id: &str) -> Result<()> { + file_common::SecretStore::delete(self.file(), id) + } +} + +impl NewKeyRing for TursoKeyring { + fn new>(lock_key: S) -> Result { + let params = lock_key.as_ref().parse::()?; + Self::with_params(¶ms, None) + } +} impl TursoKeyring { + fn file(&self) -> &TursoFile { + self.backing.file() + } + /// Open (or create) the keyring in `path` (default `~/.cryptex`). pub fn with_params(connection: &ConnectionParams, path: Option) -> Result { let file = TursoFile::open(path, builder(connection)?)?; if let Some(db_path) = file.db_path() { secure_file(db_path)?; } - Ok(Self { file, web: None }) + Ok(Self { + backing: Backing::Stored(file), + }) } /// Adopt an already-open Turso connection. @@ -132,8 +177,7 @@ impl TursoKeyring { /// ``` pub fn from_connection(conn: Connection) -> Result { Ok(Self { - file: TursoFile::adopt(conn)?, - web: None, + backing: Backing::Stored(TursoFile::adopt(conn)?), }) } @@ -149,8 +193,7 @@ impl TursoKeyring { /// sync access handle for the database. pub fn with_io(io: Arc, path: &str, params: &ConnectionParams) -> Result { Ok(Self { - file: TursoFile::open_with(builder(params)?(path).with_io_impl(io))?, - web: None, + backing: Backing::Stored(Self::open_through(io, path, params)?), }) } @@ -162,7 +205,7 @@ impl TursoKeyring { pub fn in_memory(params: &ConnectionParams) -> Result { let io = WebIo::in_memory(); let path = unique_db_path(); - Self::open_web(Arc::clone(&io), &path, params).map(|k| Self { web: Some(io), ..k }) + Self::open_web(io, &path, params) } /// Reopen a keyring from an image produced by [`export`](Self::export). @@ -173,24 +216,37 @@ impl TursoKeyring { let path = io.db_path().ok_or_else(|| KeyRingError::AccessDenied { msg: "Invalid key or corrupted keyring image".to_string(), })?; - Self::open_web(Arc::clone(&io), &path, params).map(|k| Self { web: Some(io), ..k }) + Self::open_web(io, &path, params) } + /// Open through an `IO` cryptex made, so the database can be copied out. fn open_web(io: Arc, path: &str, params: &ConnectionParams) -> Result { - let io: Arc = io; + let handle = Arc::clone(&io); // The image was already parsed, so the only thing left that can refuse // the open is the key: an image written under another key looks like a // corrupt one. Report both the way [`MemoryKeyring::import`] does. - Self::with_io(io, path, params).map_err(|_| KeyRingError::AccessDenied { - msg: "Invalid key or corrupted keyring image".to_string(), + let file = + Self::open_through(handle, path, params).map_err(|_| KeyRingError::AccessDenied { + msg: "Invalid key or corrupted keyring image".to_string(), + })?; + Ok(Self { + backing: Backing::InMemory { file, io }, }) } + fn open_through( + io: Arc, + path: &str, + params: &ConnectionParams, + ) -> Result { + TursoFile::open_with(builder(params)?(path).with_io_impl(io)) + } + /// Open (or create) the keyring in the origin private file system. /// /// Only available in a browser worker: OPFS sync access handles exist /// nowhere else. The database and its WAL live under `cryptex/.db3`. - #[cfg(feature = "opfs")] + #[cfg(feature = "turso-opfs")] pub async fn open_opfs(params: &ConnectionParams, name: &str) -> Result { let io: Arc = Arc::new(OpfsIo::open(name).await?); let keyring = Self::with_io(io, &format!("{name}.db3"), params)?; @@ -204,9 +260,8 @@ impl TursoKeyring { pub fn copy_under(&self, params: &ConnectionParams) -> Result { let io = WebIo::in_memory(); let path = unique_db_path(); - let mut copy = Self::open_web(Arc::clone(&io), &path, params)?; - copy.web = Some(io); - self.file.copy_into(©.file)?; + let copy = Self::open_web(io, &path, params)?; + self.file().copy_into(copy.file())?; Ok(copy) } @@ -215,17 +270,17 @@ impl TursoKeyring { /// Fails for a keyring opened from a path or from a caller's connection: /// the caller owns that storage, so it owns copying it. pub fn export(&self) -> Result> { - self.web - .as_ref() - .ok_or_else(|| KeyRingError::GeneralError { + match &self.backing { + Backing::InMemory { io, .. } => io.snapshot(), + Backing::Stored(_) => Err(KeyRingError::GeneralError { msg: "export is only available for an in-memory keyring".to_string(), - })? - .snapshot() + }), + } } /// Every id in the keyring, in order. pub fn keys(&self) -> Result> { - self.file.ids() + self.file().ids() } /// Re-encrypt the keyring with a new key (and optionally a different cipher). @@ -234,11 +289,13 @@ impl TursoKeyring { /// rekeying fails the original file is left intact and can be reopened /// with the old parameters. pub fn rekey(self, new_params: &ConnectionParams) -> Result { - let file = self.file.rekey(builder(new_params)?)?; + let file = self.backing.into_file().rekey(builder(new_params)?)?; if let Some(db_path) = file.db_path() { secure_file(db_path)?; } - Ok(Self { file, web: None }) + Ok(Self { + backing: Backing::Stored(file), + }) } } From 37aa80f355ddf38d3103a5e8194dae8e7c7ef1f6 Mon Sep 17 00:00:00 2001 From: Mike Lodder Date: Sat, 21 Nov 2026 07:58:19 -0700 Subject: [PATCH 16/18] fix: pass the page store mutably and keep the wasm_js cfg off WASI Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KiuMTUBySDSj38NVDFgn2b --- .github/workflows/cryptex.yml | 5 +++-- src/keyring/encrypted_vfs.rs | 3 ++- 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index c1b8528..8c4560b 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -98,14 +98,15 @@ jobs: toolchain: stable components: clippy targets: wasm32-unknown-unknown,wasm32-wasip1,wasm32-wasip2 + # WASI takes getrandom's WASI backend, so its checks drop the wasm_js cfg. - name: Check browser and WASI backends run: | cargo clippy --target wasm32-unknown-unknown --no-default-features --features turso -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-encrypted-io" -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features memory -- -D warnings cargo clippy --target wasm32-unknown-unknown --no-default-features --features "turso,turso-opfs,indexeddb,web-storage,js" -- -D warnings - cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" - cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" + RUSTFLAGS="-D warnings" cargo check --target wasm32-wasip1 --no-default-features --features "turso,memory" + RUSTFLAGS="-D warnings" cargo check --target wasm32-wasip2 --no-default-features --features "turso,memory" - name: Install wasm-pack # Pinned and built from the registry: piping an unpinned installer # script into a shell runs whatever that URL serves today. diff --git a/src/keyring/encrypted_vfs.rs b/src/keyring/encrypted_vfs.rs index 97844fa..17dbc57 100644 --- a/src/keyring/encrypted_vfs.rs +++ b/src/keyring/encrypted_vfs.rs @@ -142,7 +142,8 @@ impl Vfs for EncryptedVfs { } fn truncate(&self, handle: &mut Self::Handle, logical_size: usize) -> VfsResult<()> { - truncate(&handle.file, logical_size).map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_TRUNCATE) + truncate(&mut handle.file, logical_size) + .map_err(|_| sqlite_plugin::vars::SQLITE_IOERR_TRUNCATE) } fn read(&self, handle: &mut Self::Handle, offset: usize, data: &mut [u8]) -> VfsResult { From ef47a8e0e260a68f1b8e887e67416d5da171257a Mon Sep 17 00:00:00 2001 From: Mike Lodder Date: Sat, 21 Nov 2026 08:12:00 -0700 Subject: [PATCH 17/18] fix: bump outdated deps and isolate the nested argon2 example build argon2 0.6, dirs 7, rusqlite 0.43, sqlite-plugin 0.11, turso 0.9.0-pre.6. bindgen stays at 0.72 to match sqlite-plugin, so cargo-outdated ignores it. The argon2 example test now builds into its own target dir; sharing the unhashed rlib dropped memory and turso from the one doctests link. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KiuMTUBySDSj38NVDFgn2b --- .github/workflows/cryptex.yml | 3 ++- Cargo.toml | 12 ++++++------ tests/default_argon2_params.rs | 5 +++++ 3 files changed, 13 insertions(+), 7 deletions(-) diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index 8c4560b..3ec33d0 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -327,7 +327,8 @@ jobs: toolchain: nightly - uses: cargo-bins/cargo-binstall@main - run: cargo binstall --no-confirm cargo-outdated - - run: cargo outdated --root-deps-only --exit-code=1 + # bindgen must match sqlite-plugin's 0.72 to turn on its `runtime` feature. + - run: cargo outdated --root-deps-only --exit-code=1 --ignore bindgen pants: runs-on: ubuntu-latest diff --git a/Cargo.toml b/Cargo.toml index a8c54c5..bef4bbe 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -82,21 +82,21 @@ yubihsm-http = ["dep:yubihsm", "yubihsm/http", "yubihsm/passwords", "dep:aes-gcm [dependencies] aes-gcm = { version = "0.11", features = ["zeroize"], optional = true } -argon2 = { version = "0.5", optional = true } +argon2 = { version = "0.6", optional = true } chacha20poly1305 = { version = "0.11", features = ["zeroize"], optional = true } clap = "4.6.1" colored = "3.0" -dirs = { version = "6.0", optional = true } +dirs = { version = "7.0", optional = true } getrandom = { version = "0.4.3", optional = true } hex = "0.4" postcard = { version = "1", default-features = false, features = ["use-std"], optional = true } -rusqlite = { version = "0.40.1", default-features = false, optional = true } +rusqlite = { version = "0.43", default-features = false, optional = true } serde = { version = "1", optional = true } sha2 = { version = "0.11", optional = true } -sqlite-plugin = { version = "0.10", optional = true } +sqlite-plugin = { version = "0.11", optional = true } subtle = "2" # Pre-release pinned exactly: page encryption and custom IO are only exposed here. -turso = { version = "=0.9.0-pre.1", default-features = false, optional = true } +turso = { version = "=0.9.0-pre.6", default-features = false, optional = true } whoami = "2.1.2" yubihsm = { version = "0.42", default-features = false, optional = true } zeroize = { version = "1.9.0", features = ["zeroize_derive"] } @@ -142,7 +142,7 @@ web-sys = { version = "0.3", optional = true, features = [ # Turso's native page encryption on wasm must use its pure-Rust ciphers; # the native `aegis` build links C. [target.'cfg(all(target_arch = "wasm32", target_os = "unknown"))'.dependencies.turso] -version = "=0.9.0-pre.1" +version = "=0.9.0-pre.6" default-features = false features = ["pure-rust-crypto"] optional = true diff --git a/tests/default_argon2_params.rs b/tests/default_argon2_params.rs index 5b432ac..79cfb57 100644 --- a/tests/default_argon2_params.rs +++ b/tests/default_argon2_params.rs @@ -5,9 +5,14 @@ use std::process::Command; #[test] fn default_argon2_params_are_checked_without_test_cfg() { let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".to_string()); + // A separate target dir: the cdylib crate type leaves the rlib unhashed, so a + // nested build with fewer features would replace the one doctests link. + let target_dir = concat!(env!("CARGO_TARGET_TMPDIR"), "/default_argon2_params"); let output = Command::new(cargo) .args([ "run", + "--target-dir", + target_dir, "--quiet", "--example", "default_argon2_params", From a8e241a7b3a6551f4fec067abdba1a3834f2a8ab Mon Sep 17 00:00:00 2001 From: Mike Lodder Date: Sat, 21 Nov 2026 09:27:42 -0700 Subject: [PATCH 18/18] fix: clear the Rust 1.100 lint, gate-proof doctests and match chromedriver windows.rs uses as_chunks for the UTF-16 decode (chunks_exact_to_as_chunks). file_common doctests import file_common::ConnectionParams, which exists without the file feature. The browser tests use the runner's ChromeDriver, which matches its Chrome; setup-chrome installed a newer driver. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01KiuMTUBySDSj38NVDFgn2b --- .github/workflows/cryptex.yml | 8 +++----- src/keyring/file_common.rs | 4 ++-- src/keyring/windows.rs | 4 ++-- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/.github/workflows/cryptex.yml b/.github/workflows/cryptex.yml index 3ec33d0..b5ffc59 100644 --- a/.github/workflows/cryptex.yml +++ b/.github/workflows/cryptex.yml @@ -113,12 +113,10 @@ jobs: run: cargo install wasm-pack --locked --version 0.13.1 - name: Build the JavaScript package run: wasm-pack build --target web --no-default-features --features js - - name: Set up Chrome and ChromeDriver - uses: browser-actions/setup-chrome@v1 - with: - install-chromedriver: true + # The runner image ships Chrome with a matching ChromeDriver; a separately + # installed driver tracks a newer Chrome and refuses the image's browser. - name: Run the browser tests - run: wasm-pack test --headless --chrome --no-default-features --features js --test wasm + run: wasm-pack test --headless --chrome --chromedriver "$CHROMEWEBDRIVER/chromedriver" --no-default-features --features js --test wasm rustfmt-linux: runs-on: ubuntu-latest diff --git a/src/keyring/file_common.rs b/src/keyring/file_common.rs index 2cb9002..3e3cc7f 100644 --- a/src/keyring/file_common.rs +++ b/src/keyring/file_common.rs @@ -182,7 +182,7 @@ impl CipherParam for NoCipher { /// similar to postgres. /// /// ``` -/// use cryptex::sqlcipher::ConnectionParams; +/// use cryptex::file_common::ConnectionParams; /// /// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv".parse::().unwrap(); /// ``` @@ -190,7 +190,7 @@ impl CipherParam for NoCipher { /// or with extra parameters. `memory` is Argon2's memory cost in KiB blocks. /// /// ``` -/// use cryptex::sqlcipher::ConnectionParams; +/// use cryptex::file_common::ConnectionParams; /// /// let params = "password=1qaz2wsx3edc4rfv salt=0okm9ijn8uhb7ygv memory=32768 threads=3 parallel=2".parse::().unwrap(); /// ``` diff --git a/src/keyring/windows.rs b/src/keyring/windows.rs index 46e6910..a4ecffa 100644 --- a/src/keyring/windows.rs +++ b/src/keyring/windows.rs @@ -256,8 +256,8 @@ unsafe fn get_credentials( let secret = unsafe { std::slice::from_raw_parts(blob, blob_len) }; let mut secret_u16 = vec![0u16; blob_len / 2]; - for (i, chunk) in secret.chunks_exact(2).enumerate() { - secret_u16[i] = u16::from_le_bytes([chunk[0], chunk[1]]); + for (i, chunk) in secret.as_chunks::<2>().0.iter().enumerate() { + secret_u16[i] = u16::from_le_bytes(*chunk); } let t = match String::from_utf16(secret_u16.as_slice()).map(|pass| pass.to_string()) { Ok(s) => s,