use super::*;
#[cfg(not(feature = "fips"))]
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 = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
use std::fs::OpenOptions;
#[cfg(any(
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
use std::fs::{File, 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 zeroize::{Zeroize, Zeroizing};
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
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"
))]
pub(crate) const SELECT_IDS_SQL: &str = "SELECT id FROM secrets ORDER BY id";
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
pub(crate) trait SecretStore {
fn get(&self, id: &str) -> Result<KeyRingSecret>;
fn set(&self, id: &str, secret: &[u8]) -> Result<()>;
fn delete(&self, id: &str) -> Result<()>;
fn ids(&self) -> Result<Vec<String>>;
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
pub(crate) fn decode_secret(value: Option<Zeroizing<String>>) -> Result<KeyRingSecret> {
let value = value.ok_or(KeyRingError::ItemNotFound)?;
hex::decode(value.as_str())
.map(KeyRingSecret)
.map_err(|e| KeyRingError::GeneralError {
msg: format!("corrupt secret encoding: {}", e),
})
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
pub(crate) fn invalid_key() -> KeyRingError {
KeyRingError::AccessDenied {
msg: "Invalid key or corrupted database".to_string(),
}
}
#[allow(unused_macros)]
macro_rules! file_keyring {
($keyring:ty, $store:ident) => {
impl $crate::DynKeyRing for $keyring {
fn get_secret(&mut self, id: &str) -> $crate::Result<$crate::KeyRingSecret> {
$crate::file_common::SecretStore::get(&self.$store, id)
}
fn set_secret(&mut self, id: &str, secret: &[u8]) -> $crate::Result<()> {
$crate::file_common::SecretStore::set(&self.$store, id, secret)
}
fn delete_secret(&mut self, id: &str) -> $crate::Result<()> {
$crate::file_common::SecretStore::delete(&self.$store, id)
}
}
impl $keyring {
pub fn keys(&self) -> $crate::Result<Vec<String>> {
$crate::file_common::SecretStore::ids(&self.$store)
}
}
impl $crate::NewKeyRing for $keyring {
fn new<S: AsRef<str>>(lock_key: S) -> $crate::Result<Self> {
let params = lock_key.as_ref().parse::<ConnectionParams>()?;
Self::with_params(¶ms, None)
}
}
};
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso-encrypted-io",
feature = "yubihsm-usb",
feature = "yubihsm-http"
))]
pub(crate) use file_keyring;
pub trait CipherParam: Copy + Default + Zeroize {
fn parse(value: &str) -> Result<Self>;
}
#[derive(Clone, Copy, Default, Debug, PartialEq, Eq, Zeroize)]
pub struct NoCipher;
impl CipherParam for NoCipher {
fn parse(_value: &str) -> Result<Self> {
Err(KeyRingError::GeneralError {
msg: "cipher is not configurable for this keyring".to_string(),
})
}
}
#[derive(Zeroize)]
pub struct ConnectionParams<C: CipherParam = NoCipher> {
pub key: Vec<u8>,
pub password: Vec<u8>,
pub salt: Vec<u8>,
pub memory: u32,
pub threads: u32,
pub parallel: u32,
#[cfg(feature = "fips")]
pub iterations: u32,
pub cipher: C,
}
impl<C: CipherParam> Default for ConnectionParams<C> {
fn default() -> Self {
Self {
key: vec![],
password: vec![],
salt: vec![],
memory: default_memory_cost(),
threads: default_threads(),
parallel: default_parallel(),
#[cfg(feature = "fips")]
iterations: default_iterations(),
cipher: C::default(),
}
}
}
impl<C: CipherParam> Drop for ConnectionParams<C> {
fn drop(&mut self) {
self.key.zeroize();
self.password.zeroize();
self.salt.zeroize();
}
}
impl<C: CipherParam> FromStr for ConnectionParams<C> {
type Err = KeyRingError;
fn from_str(s: &str) -> Result<Self> {
Parser::parse(s)
}
}
impl<C: CipherParam> ConnectionParams<C> {
fn param(&mut self, key: &str, value: &str) -> Result<()> {
match key {
"key" => {
self.key = hex::decode(value).map_err(|_| KeyRingError::GeneralError {
msg: "invalid hex key".to_string(),
})?
}
"password" => self.password = value.as_bytes().to_vec(),
"salt" => self.salt = value.as_bytes().to_vec(),
"cipher" => self.cipher = C::parse(value)?,
#[cfg(not(feature = "fips"))]
"memory" => {
self.memory = parse_cost(
"memory",
value,
Argon2Params::DEFAULT_M_COST,
Argon2Params::MAX_M_COST,
)?
}
#[cfg(not(feature = "fips"))]
"threads" => {
self.threads = parse_cost(
"threads",
value,
Argon2Params::DEFAULT_T_COST,
Argon2Params::MAX_T_COST,
)?
}
#[cfg(not(feature = "fips"))]
"parallel" => {
self.parallel = parse_cost(
"parallel",
value,
Argon2Params::DEFAULT_P_COST,
Argon2Params::MAX_P_COST,
)?
}
#[cfg(feature = "fips")]
"iterations" => {
self.iterations =
parse_cost("iterations", value, default_iterations(), MAX_ITERATIONS)?
}
_ => {
return Err(KeyRingError::GeneralError {
msg: format!("unknown parameter: {}", key),
});
}
};
Ok(())
}
pub fn key(&mut self, key: &[u8]) -> &mut Self {
self.key = key.to_vec();
self
}
pub fn password(&mut self, password: &[u8]) -> &mut Self {
self.password = password.to_vec();
self
}
pub fn salt(&mut self, salt: &[u8]) -> &mut Self {
self.salt = salt.to_vec();
self
}
pub fn memory(&mut self, cost: u32) -> &mut Self {
self.memory = cost;
self
}
pub fn time(&mut self, cost: u32) -> &mut Self {
self.threads = cost;
self
}
pub fn parallel(&mut self, cost: u32) -> &mut Self {
self.parallel = cost;
self
}
}
#[cfg(any(
feature = "memory",
feature = "encrypted-vfs",
feature = "turso-encrypted-io"
))]
impl<C: CipherParam> ConnectionParams<C> {
pub(crate) fn kdf_costs(&self) -> [u32; 3] {
#[cfg(not(feature = "fips"))]
return [self.memory, self.threads, self.parallel];
#[cfg(feature = "fips")]
return [self.iterations, 0, 0];
}
pub(crate) fn set_kdf_costs(&mut self, costs: [u32; 3]) {
#[cfg(not(feature = "fips"))]
{
[self.memory, self.threads, self.parallel] = costs;
}
#[cfg(feature = "fips")]
{
self.iterations = costs[0];
}
}
}
#[cfg(any(
feature = "memory",
feature = "encrypted-vfs",
feature = "turso-encrypted-io"
))]
pub(crate) fn check_stored_kdf_costs(costs: [u32; 3]) -> Result<()> {
#[cfg(not(feature = "fips"))]
let reasonable = {
let [memory, threads, parallel] = costs;
memory <= 1024 * 1024 && threads <= 64 && parallel <= 64
};
#[cfg(feature = "fips")]
let reasonable = costs[0] <= MAX_ITERATIONS;
if reasonable {
Ok(())
} else {
Err(KeyRingError::GeneralError {
msg: "the stored key derivation costs are unreasonable".to_string(),
})
}
}
fn parse_cost(name: &str, value: &str, min: u32, max: u32) -> Result<u32> {
let cost = value
.parse::<u32>()
.map_err(|e| KeyRingError::GeneralError {
msg: format!("expected an integer for {}: {}", name, e),
})?;
if !(min..max).contains(&cost) {
return Err(KeyRingError::GeneralError {
msg: format!(
"invalid value for {} must be between {} and {}",
name, min, max
),
});
}
Ok(cost)
}
pub(crate) fn derive_key<C: CipherParam>(
params: &ConnectionParams<C>,
) -> Result<Zeroizing<Vec<u8>>> {
if !params.key.is_empty() {
return Ok(Zeroizing::new(params.key.to_vec()));
}
password_key(params)
}
#[cfg(feature = "fips")]
pub(crate) const MAX_ITERATIONS: u32 = 100_000_000;
#[cfg(feature = "fips")]
const MIN_SALT_LEN: usize = 16;
#[cfg(feature = "fips")]
fn password_key<C: CipherParam>(params: &ConnectionParams<C>) -> Result<Zeroizing<Vec<u8>>> {
if params.salt.len() < MIN_SALT_LEN {
return Err(KeyRingError::GeneralError {
msg: format!("salt must be at least {} bytes", MIN_SALT_LEN),
});
}
if !(default_iterations()..=MAX_ITERATIONS).contains(¶ms.iterations) {
return Err(KeyRingError::GeneralError {
msg: format!(
"iterations must be between {} and {}",
default_iterations(),
MAX_ITERATIONS
),
});
}
let mut okm = Zeroizing::new(vec![0u8; 32]);
pbkdf2::pbkdf2_hmac::<sha2::Sha256>(
¶ms.password,
¶ms.salt,
params.iterations,
&mut okm,
);
Ok(okm)
}
#[cfg(not(feature = "fips"))]
fn password_key<C: CipherParam>(params: &ConnectionParams<C>) -> Result<Zeroizing<Vec<u8>>> {
let argon2_params = Argon2Params::new(
params.memory,
params.threads,
params.parallel,
Some(Argon2Params::DEFAULT_OUTPUT_LEN),
)
.map_err(|e| KeyRingError::GeneralError {
msg: format!("invalid Argon2 parameters: {}", e),
})?;
let argon2 = Argon2::new(Algorithm::Argon2id, Version::V0x13, argon2_params);
let mut okm = Zeroizing::new(vec![0u8; 32]);
argon2
.hash_password_into(¶ms.password, ¶ms.salt, &mut okm)
.map_err(|e| KeyRingError::GeneralError {
msg: format!("Argon2 key derivation failed: {}", e),
})?;
Ok(okm)
}
#[cfg(any(
feature = "encrypted-vfs",
feature = "memory",
feature = "turso",
feature = "turso-encrypted-io"
))]
pub(crate) fn derive_key_32<C: CipherParam>(
params: &ConnectionParams<C>,
) -> Result<Zeroizing<[u8; 32]>> {
let key = derive_key(params)?;
let mut out = Zeroizing::new([0u8; 32]);
if key.len() != out.len() {
return Err(KeyRingError::GeneralError {
msg: "key must be 32 bytes".to_string(),
});
}
out.copy_from_slice(&key);
Ok(out)
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io",
))]
pub(crate) fn get_keyring_file(in_path: Option<PathBuf>, file_name: &str) -> Result<PathBuf> {
let is_default = in_path.is_none();
let mut path = match in_path {
None => {
#[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()
.or_else(dirs::document_dir)
.or_else(dirs::data_local_dir)
.ok_or_else(|| KeyRingError::GeneralError {
msg: "no home directory to keep the keyring in; pass a path".to_string(),
})?;
path.push(format!(".{}", env!("CARGO_PKG_NAME")));
path
}
Some(path) => path,
};
let created = !path.is_dir();
if created {
fs::create_dir_all(&path).map_err(|e| KeyRingError::GeneralError {
msg: format!("unable to create folder {}: {}", path.display(), e),
})?;
}
if is_default || created {
secure_dir(&path)?;
make_hidden(&path);
}
path.push(file_name);
Ok(path)
}
#[cfg(any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
pub(crate) fn private_open_options() -> OpenOptions {
let mut opts = OpenOptions::new();
restrict_to_owner(&mut opts);
opts
}
#[cfg(all(
unix,
any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
)
))]
fn restrict_to_owner(opts: &mut OpenOptions) {
use std::os::unix::fs::OpenOptionsExt;
opts.mode(0o600);
}
#[cfg(all(
not(unix),
any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
)
))]
fn restrict_to_owner(_opts: &mut OpenOptions) {}
#[cfg(any(
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
pub(crate) fn acquire_single_opener_lock(db_path: &Path) -> Result<File> {
let lock_path = sibling_path(db_path, ".lock");
let file = private_open_options()
.read(true)
.write(true)
.create(true)
.truncate(false)
.open(&lock_path)
.map_err(|e| KeyRingError::GeneralError {
msg: format!(
"unable to open keyring lock file {}: {}",
lock_path.display(),
e
),
})?;
match file.try_lock() {
Ok(()) => Ok(file),
Err(TryLockError::WouldBlock) => Err(KeyRingError::AccessDenied {
msg: "keyring is already open by another process".to_string(),
}),
#[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),
}),
}
}
#[cfg(all(
unix,
any(
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
)
))]
pub(crate) fn sync_parent_dir(path: &Path) -> Result<()> {
match path.parent() {
Some(dir) => Ok(File::open(dir)?.sync_all()?),
None => Ok(()),
}
}
#[cfg(all(
not(unix),
any(
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
)
))]
pub(crate) fn sync_parent_dir(_path: &Path) -> Result<()> {
Ok(())
}
#[cfg(any(
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
))]
pub(crate) fn sibling_path(path: &Path, suffix: &str) -> PathBuf {
let mut s = path.as_os_str().to_os_string();
s.push(suffix);
PathBuf::from(s)
}
#[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;
fs::set_permissions(path, fs::Permissions::from_mode(0o700)).map_err(|e| {
KeyRingError::GeneralError {
msg: format!("unable to secure folder {}: {}", path.display(), e),
}
})
}
#[cfg(all(
not(unix),
any(
feature = "file",
feature = "encrypted-vfs",
feature = "turso",
feature = "turso-encrypted-io"
)
))]
fn secure_dir(_path: &Path) -> Result<()> {
Ok(())
}
#[cfg(any(feature = "file", feature = "turso", feature = "turso-encrypted-io"))]
pub(crate) fn create_private_file(path: &Path) -> Result<()> {
private_open_options()
.write(true)
.create(true)
.truncate(false)
.open(path)
.map(drop)
.map_err(|e| KeyRingError::GeneralError {
msg: format!("unable to create keyring file {}: {}", path.display(), e),
})
}
#[cfg(all(unix, any(feature = "file", feature = "turso")))]
pub(crate) fn secure_file(path: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
fs::set_permissions(path, fs::Permissions::from_mode(0o600)).map_err(|e| {
KeyRingError::GeneralError {
msg: format!("unable to secure keyring file {}: {}", path.display(), e),
}
})
}
#[cfg(all(not(unix), any(feature = "file", feature = "turso")))]
pub(crate) fn secure_file(_path: &Path) -> Result<()> {
Ok(())
}
#[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;
const FILE_ATTRIBUTE_HIDDEN: u32 = 0x2;
unsafe extern "system" {
fn SetFileAttributesW(lpfilename: *const u16, dwfileattributes: u32) -> i32;
}
let wide: Vec<u16> = OsStr::new(path)
.encode_wide()
.chain(iter::once(0))
.collect();
unsafe {
SetFileAttributesW(wide.as_ptr(), FILE_ATTRIBUTE_HIDDEN);
}
}
#[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> {
s: &'a str,
it: iter::Peekable<std::str::CharIndices<'a>>,
}
impl<'a> Parser<'a> {
fn parse<C: CipherParam>(s: &'a str) -> Result<ConnectionParams<C>> {
let mut parser = Parser {
s,
it: s.char_indices().peekable(),
};
let mut connection_string = ConnectionParams::default();
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)
}
fn skip_ws(&mut self) {
self.take_while(char::is_whitespace);
}
fn take_while<F>(&mut self, f: F) -> &'a str
where
F: Fn(char) -> bool,
{
let start = match self.it.peek() {
Some(&(i, _)) => i,
None => return "",
};
loop {
match self.it.peek() {
Some(&(_, c)) if f(c) => {
self.it.next();
}
Some(&(i, _)) => return &self.s[start..i],
None => return &self.s[start..],
}
}
}
fn consume(&mut self, target: char) -> Result<()> {
match self.it.next() {
Some((_, c)) if c == target => Ok(()),
Some((i, _)) => Err(KeyRingError::GeneralError {
msg: format!("unexpected character at byte {}: expected `{}`", i, target),
}),
None => Err(KeyRingError::GeneralError {
msg: "unexpected EOF".to_string(),
}),
}
}
fn consume_if(&mut self, target: char) -> bool {
match self.it.peek() {
Some(&(_, c)) if c == target => {
self.it.next();
true
}
_ => false,
}
}
fn keyword(&mut self) -> Option<&'a str> {
let s = self.take_while(|c| !c.is_whitespace() && c != '=');
if s.is_empty() { None } else { Some(s) }
}
fn value(&mut self) -> Result<Zeroizing<String>> {
if self.consume_if('\'') {
let value = self.quoted_value()?;
self.consume('\'')?;
Ok(value)
} else {
self.simple_value()
}
}
fn simple_value(&mut self) -> Result<Zeroizing<String>> {
let mut value = Zeroizing::new(String::with_capacity(self.s.len()));
while let Some(&(_, c)) = self.it.peek() {
if c.is_whitespace() {
break;
}
self.it.next();
if c == '\\' {
if let Some((_, c2)) = self.it.next() {
value.push(c2);
}
} else {
value.push(c);
}
}
if value.is_empty() {
return Err(KeyRingError::GeneralError {
msg: "unexpected EOF".to_string(),
});
}
Ok(value)
}
fn quoted_value(&mut self) -> Result<Zeroizing<String>> {
let mut value = Zeroizing::new(String::with_capacity(self.s.len()));
while let Some(&(_, c)) = self.it.peek() {
if c == '\'' {
return Ok(value);
}
self.it.next();
if c == '\\' {
if let Some((_, c2)) = self.it.next() {
value.push(c2);
}
} else {
value.push(c);
}
}
Err(KeyRingError::GeneralError {
msg: "unterminated quoted connection parameter value".to_string(),
})
}
fn parameter(&mut self) -> Result<Option<(&'a str, Zeroizing<String>)>> {
self.skip_ws();
let keyword = match self.keyword() {
Some(keyword) => keyword,
None => return Ok(None),
};
self.skip_ws();
self.consume('=')?;
self.skip_ws();
let value = self.value()?;
Ok(Some((keyword, value)))
}
}
#[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};
pub(crate) struct TestDir(PathBuf);
impl TestDir {
pub(crate) fn new(name: &str) -> Self {
#[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)
}
pub(crate) fn keyring_dir(&self) -> Option<PathBuf> {
Some(self.0.clone())
}
}
impl Deref for TestDir {
type Target = Path;
fn deref(&self) -> &Path {
&self.0
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
}
#[cfg(test)]
mod tests {
use super::{ConnectionParams, NoCipher, derive_key};
#[cfg(not(feature = "fips"))]
#[test]
fn parses_all_fields() {
let p: ConnectionParams = "password=pw salt='a b' memory=32768 threads=3 parallel=2"
.parse()
.unwrap();
assert_eq!(p.password, b"pw");
assert_eq!(p.salt, b"a b");
assert_eq!((p.memory, p.threads, p.parallel), (32768, 3, 2));
assert_eq!(p.cipher, NoCipher);
}
#[cfg(feature = "fips")]
#[test]
fn fips_parses_iterations_and_refuses_argon2_costs() {
let p: ConnectionParams = "password=pw salt='a b' iterations=700000".parse().unwrap();
assert_eq!(p.iterations, 700_000);
assert_eq!(p.cipher, NoCipher);
for s in ["memory=32768", "threads=3", "parallel=2", "iterations=1"] {
assert!(s.parse::<ConnectionParams>().is_err(), "accepted: {s}");
}
}
#[cfg(feature = "fips")]
#[test]
fn fips_refuses_short_salts() {
let p: ConnectionParams = "password=pw salt=fifteen-bytes!!".parse().unwrap();
assert!(derive_key(&p).is_err());
}
#[test]
fn rejects_bad_input() {
for s in [
"key=not-hex",
"cipher=aes256gcm",
"unknown=1",
"memory=abc",
"threads=0",
"password='unterminated",
"password",
] {
assert!(s.parse::<ConnectionParams>().is_err(), "accepted: {s}");
}
}
#[test]
fn errors_do_not_echo_secret_characters() {
for (s, leaked) in [("password=pw salt Q", 'Q'), ("key=zz", 'z')] {
let err = s.parse::<ConnectionParams>().err().unwrap().to_string();
assert!(!err.contains(leaked), "{err}");
}
}
#[test]
fn raw_key_bypasses_argon2() {
let p: ConnectionParams = "key=aabb".parse().unwrap();
assert_eq!(&*derive_key(&p).unwrap(), &[0xaa, 0xbb]);
}
#[test]
fn password_derivation_is_deterministic() {
let a: ConnectionParams = "password=pw salt=saltsaltsaltsalt".parse().unwrap();
let b: ConnectionParams = "password=pw salt=saltsaltsaltsalt".parse().unwrap();
let c: ConnectionParams = "password=pw2 salt=saltsaltsaltsalt".parse().unwrap();
let ka = derive_key(&a).unwrap();
assert_eq!(ka.len(), 32);
assert_eq!(ka, derive_key(&b).unwrap());
assert_ne!(ka, derive_key(&c).unwrap());
}
#[cfg(all(unix, feature = "file"))]
#[test]
fn caller_folder_permissions_are_left_alone() {
use super::get_keyring_file;
use super::test_support::TestDir;
use std::os::unix::fs::PermissionsExt;
let dir = TestDir::new(".test-caller-folder-mode");
std::fs::create_dir_all(&*dir).unwrap();
std::fs::set_permissions(&*dir, std::fs::Permissions::from_mode(0o755)).unwrap();
get_keyring_file(dir.keyring_dir(), "k.db3").unwrap();
let mode = std::fs::metadata(&*dir).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o755);
let created = dir.join("new");
get_keyring_file(Some(created.clone()), "k.db3").unwrap();
let mode = std::fs::metadata(&created).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o700);
}
#[cfg(all(unix, feature = "file"))]
#[test]
fn private_file_is_owner_only_and_keeps_content() {
use super::create_private_file;
use super::test_support::TestDir;
use std::os::unix::fs::PermissionsExt;
let dir = TestDir::new(".test-private-file");
std::fs::create_dir_all(&*dir).unwrap();
let path = dir.join("k.db3");
create_private_file(&path).unwrap();
let mode = std::fs::metadata(&path).unwrap().permissions().mode() & 0o777;
assert_eq!(mode, 0o600);
std::fs::write(&path, b"existing").unwrap();
create_private_file(&path).unwrap();
assert_eq!(std::fs::read(&path).unwrap(), b"existing");
}
}