use std::sync::Arc;
use rusqlite::Connection;
use super::cells;
use super::scope::Scope;
use super::value::Raw;
use crate::encryption::EncryptionKey;
use crate::{Error, Result};
const NOTHING: u8 = 0;
const INTEGER: u8 = 1;
const BYTES: u8 = 2;
#[derive(Clone)]
pub(crate) struct Encrypted {
key: Arc<EncryptionKey>,
bucket: i64,
place: Arc<[u8]>,
}
impl Encrypted {
pub(crate) fn of(scope: &Scope) -> Result<Encrypted> {
let opened = || {
let kept = scope.kv.file().read(|connection| cells::bucket_key(connection, scope.id))?;
scope.kv.encryption_key(kept.as_deref())
};
let key = opened().map_err(|error| error.within(scope.shown()))?;
let place = [scope.kv.place().as_bytes(), &[0], scope.name().as_bytes(), &[0]].concat();
Ok(Encrypted { key, bucket: scope.id, place: place.into() })
}
pub(crate) fn claim(&self, connection: &Connection) -> Result<()> {
let mine = self.key.id();
match cells::bucket_key(connection, self.bucket)? {
Some(kept) if kept == mine => Ok(()),
Some(kept) => Err(Error::invalid(format!(
"its bucket's values are encrypted with the key {kept}, and the store's is {mine}: \
open the store with that key, or clear the bucket to start it again with this one"
))),
None => cells::keep_bucket_key(connection, self.bucket, Some(&mine)),
}
}
#[cfg(feature = "replication")]
pub(crate) fn key_id(&self) -> String {
self.key.id()
}
pub(crate) fn seal(&self, path: &[u8], raw: &Raw) -> Result<Raw> {
let value = match raw {
Raw::None => vec![NOTHING],
Raw::Int(int) => [&[INTEGER][..], &int.to_be_bytes()].concat(),
Raw::Bytes(bytes) => [&[BYTES][..], bytes].concat(),
};
self.key.seal(&self.at(path), &value).map(Raw::Bytes)
}
pub(crate) fn open(&self, path: &[u8], kept: &Raw) -> Result<Raw> {
let Raw::Bytes(sealed) = kept else {
return Err(Error::corrupt("its value is not one the store encrypted"));
};
let value = self.key.open(&self.at(path), sealed)?;
match value.split_first() {
Some((&NOTHING, [])) => Ok(Raw::None),
Some((&INTEGER, int)) => match <[u8; 8]>::try_from(int) {
Ok(int) => Ok(Raw::Int(i64::from_be_bytes(int))),
Err(_) => Err(Error::corrupt("its encrypted value is an integer of another size")),
},
Some((&BYTES, bytes)) => Ok(Raw::Bytes(bytes.to_vec())),
_ => Err(Error::corrupt("its encrypted value is of no kind a row is")),
}
}
fn at(&self, path: &[u8]) -> Vec<u8> {
[&self.place[..], path].concat()
}
}
#[cfg(test)]
#[path = "encrypted_tests.rs"]
mod tests;