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, secure_file};
#[cfg(feature = "turso-opfs")]
use super::opfs::OpfsIo;
use super::turso_common::TursoFile;
use super::turso_web::{WebIo, unique_db_path};
use crate::error::KeyRingError;
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
pub enum TursoCipher {
#[default]
Aegis256,
Aes256Gcm,
}
impl TursoCipher {
fn as_turso_name(self) -> &'static str {
match self {
TursoCipher::Aegis256 => "aegis256",
TursoCipher::Aes256Gcm => "aes256gcm",
}
}
}
impl Zeroize for TursoCipher {
fn zeroize(&mut self) {
*self = TursoCipher::default();
}
}
impl CipherParam for TursoCipher {
fn parse(value: &str) -> Result<Self> {
match value {
"aegis256" | "aegis" => Ok(TursoCipher::Aegis256),
"aes256gcm" | "aes" => Ok(TursoCipher::Aes256Gcm),
other => Err(KeyRingError::GeneralError {
msg: format!("unknown cipher '{}'; use aegis256 or aes256gcm", other),
}),
}
}
}
pub type ConnectionParams = file_common::ConnectionParams<TursoCipher>;
pub use ::turso::Builder as TursoBuilder;
pub use ::turso::Connection;
pub use ::turso::core;
pub struct TursoKeyring {
backing: Backing,
}
enum Backing {
Stored(TursoFile),
InMemory { file: TursoFile, io: Arc<WebIo> },
}
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<KeyRingSecret> {
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<S: AsRef<str>>(lock_key: S) -> Result<Self> {
let params = lock_key.as_ref().parse::<ConnectionParams>()?;
Self::with_params(¶ms, None)
}
}
impl TursoKeyring {
fn file(&self) -> &TursoFile {
self.backing.file()
}
pub fn with_params(connection: &ConnectionParams, path: Option<PathBuf>) -> Result<Self> {
let file = TursoFile::open(path, builder(connection)?)?;
if let Some(db_path) = file.db_path() {
secure_file(db_path)?;
}
Ok(Self {
backing: Backing::Stored(file),
})
}
pub fn from_connection(conn: Connection) -> Result<Self> {
Ok(Self {
backing: Backing::Stored(TursoFile::adopt(conn)?),
})
}
pub fn with_io(io: Arc<dyn core::IO>, path: &str, params: &ConnectionParams) -> Result<Self> {
Ok(Self {
backing: Backing::Stored(Self::open_through(io, path, params)?),
})
}
pub fn in_memory(params: &ConnectionParams) -> Result<Self> {
let io = WebIo::in_memory();
let path = unique_db_path();
Self::open_web(io, &path, params)
}
pub fn from_bytes(bytes: &[u8], params: &ConnectionParams) -> Result<Self> {
let io = WebIo::restore(bytes)?;
let path = io.db_path().ok_or_else(|| KeyRingError::AccessDenied {
msg: "Invalid key or corrupted keyring image".to_string(),
})?;
Self::open_web(io, &path, params)
}
fn open_web(io: Arc<WebIo>, path: &str, params: &ConnectionParams) -> Result<Self> {
let handle = Arc::clone(&io);
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<dyn core::IO>,
path: &str,
params: &ConnectionParams,
) -> Result<TursoFile> {
TursoFile::open_with(builder(params)?(path).with_io_impl(io))
}
#[cfg(feature = "turso-opfs")]
pub async fn open_opfs(params: &ConnectionParams, name: &str) -> Result<Self> {
let io: Arc<dyn core::IO> = Arc::new(OpfsIo::open(name).await?);
let keyring = Self::with_io(io, &format!("{name}.db3"), params)?;
Ok(keyring)
}
pub fn copy_under(&self, params: &ConnectionParams) -> Result<Self> {
let io = WebIo::in_memory();
let path = unique_db_path();
let copy = Self::open_web(io, &path, params)?;
self.file().copy_into(copy.file())?;
Ok(copy)
}
pub fn export(&self) -> Result<Vec<u8>> {
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(),
}),
}
}
pub fn keys(&self) -> Result<Vec<String>> {
self.file().ids()
}
pub fn rekey(self, new_params: &ConnectionParams) -> Result<Self> {
let file = self.backing.into_file().rekey(builder(new_params)?)?;
if let Some(db_path) = file.db_path() {
secure_file(db_path)?;
}
Ok(Self {
backing: Backing::Stored(file),
})
}
}
fn builder(params: &ConnectionParams) -> Result<impl Fn(&str) -> Builder> {
let hexkey = Zeroizing::new(hex::encode(*derive_key_32(params)?));
let cipher = params.cipher.as_turso_name();
Ok(move |path: &str| {
Builder::new_local(path)
.experimental_encryption(true)
.with_encryption(EncryptionOpts {
cipher: cipher.to_string(),
hexkey: hexkey.to_string(),
})
})
}
#[cfg(test)]
mod tests {
use super::{ConnectionParams, TursoCipher, TursoKeyring};
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()
}
fn with_paths(image: &[u8], base: &str) -> Vec<u8> {
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);
assert_eq!(
params("password=a cipher=aes256gcm").cipher,
TursoCipher::Aes256Gcm
);
assert!("cipher=chacha20".parse::<ConnectionParams>().is_err());
}
#[test]
fn works() {
let dir = TestDir::new(".test-turso-works");
let p = params("password=works_test salt=1qaz2wsx3edc4rfv5tgb");
{
let mut kr = TursoKeyring::with_params(&p, dir.keyring_dir()).unwrap();
kr.set_secret("k1", b"value1").unwrap();
assert_eq!(kr.get_secret("k1").unwrap().0, b"value1");
kr.set_secret("k1", b"value2").unwrap();
assert_eq!(kr.get_secret("k1").unwrap().0, b"value2");
kr.delete_secret("k1").unwrap();
assert!(matches!(
kr.get_secret("k1"),
Err(KeyRingError::ItemNotFound)
));
kr.set_secret("persist", b"persisted").unwrap();
}
{
let mut kr = TursoKeyring::with_params(&p, dir.keyring_dir()).unwrap();
assert_eq!(kr.get_secret("persist").unwrap().0, b"persisted");
}
let raw = fs::read(dir.join("keyring-turso.db3")).unwrap();
assert!(!raw.windows(9).any(|w| w == b"persisted"));
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_eq!(restored.keys().unwrap(), ["k1", "shared"]);
assert!(matches!(
TursoKeyring::from_bytes(&image, &wrong),
Err(KeyRingError::AccessDenied { .. })
));
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;
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());
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;
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() {
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();
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)
));
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");
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());
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");
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");
let correct = params("password=correct_password salt=1qaz2wsx3edc4rfv5tgb");
let wrong = params("password=wrong_password salt=1qaz2wsx3edc4rfv5tgb");
{
let mut kr = TursoKeyring::with_params(&correct, dir.keyring_dir()).unwrap();
kr.set_secret("x", b"secret").unwrap();
#[cfg(not(target_os = "wasi"))]
assert!(matches!(
TursoKeyring::with_params(&correct, dir.keyring_dir()),
Err(KeyRingError::AccessDenied { .. })
));
}
assert!(TursoKeyring::with_params(&wrong, dir.keyring_dir()).is_err());
}
#[test]
fn rekey_works() {
let dir = TestDir::new(".test-turso-rekey");
let old_params = params("password=old_pass salt=old_salt_value_here_");
let new_params = params("password=new_pass salt=new_salt_value_here_ cipher=aes256gcm");
{
let mut kr = TursoKeyring::with_params(&old_params, dir.keyring_dir()).unwrap();
for i in 0..50 {
kr.set_secret(format!("key_{i}"), format!("value_{i}"))
.unwrap();
}
let mut kr = kr.rekey(&new_params).unwrap();
kr.set_secret("after", b"after_rekey").unwrap();
assert_eq!(kr.get_secret("key_7").unwrap().0, b"value_7");
}
{
let mut kr = TursoKeyring::with_params(&new_params, dir.keyring_dir()).unwrap();
for i in 0..50 {
assert_eq!(
kr.get_secret(format!("key_{i}")).unwrap().0,
format!("value_{i}").as_bytes()
);
}
assert_eq!(kr.get_secret("after").unwrap().0, b"after_rekey");
}
assert!(TursoKeyring::with_params(&old_params, dir.keyring_dir()).is_err());
}
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);
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)
));
}
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::<String>(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() {
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");
}
let wrong = params("password=wrong_pass salt=1qaz2wsx3edc4rfv5tgb");
assert!(TursoKeyring::with_io(io, db_name, &wrong).is_err());
}
}