use std::{
collections::HashSet,
fmt::Display,
io::{Cursor, Write},
marker::PhantomData,
num::NonZero,
ops::{Add, Sub},
path::Path,
time::{Duration, SystemTime},
};
use digest::Digest;
use educe::Educe;
use flate2::write::{DeflateEncoder, GzEncoder};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rand::Rng;
use rusqlite::{
OptionalExtension, ToSql, Transaction, TransactionBehavior, named_params, params,
types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef},
};
use saturating_time::SaturatingTime;
use tor_basic_utils::RngExt;
use tor_dircommon::config::DirTolerance;
use tor_error::into_internal;
use tor_netdoc::doc::{
authcert::{AuthCert, AuthCertKeyIds},
netstatus::ConsensusFlavor,
};
use crate::{err::DatabaseError, types::FlavoredConsensusUnverified};
const V1_SCHEMA: &str = include_str!("schema_v1.sql");
const GLOBAL_OPTIONS: &str = sql!(
"
PRAGMA journal_mode=WAL;
PRAGMA foreign_keys=ON;
PRAGMA busy_timeout=1000;
"
);
macro_rules! impl_hash_wrapper {
($name:ident, $algo:ty, $size:literal) => {
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct $name([u8; $size]);
impl $name {
pub(crate) fn digest(data: &[u8]) -> Self {
Self(<$algo>::digest(data).into())
}
}
impl Display for $name {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", hex::encode_upper(self.0))
}
}
impl FromSql for $name {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let data: [u8; $size] = value
.as_str()
.map(hex::decode)?
.map_err(|e| {
FromSqlError::Other(Box::new(tor_error::internal!(
"non hex data in database? {e}"
)))
})?
.try_into()
.map_err(|_| {
FromSqlError::Other(Box::new(tor_error::internal!(
"$name with invalid length in database?"
)))
})?;
Ok(Self(data))
}
}
impl ToSql for $name {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
Ok(ToSqlOutput::from(self.to_string()))
}
}
impl PartialEq<&str> for $name {
fn eq(&self, other: &&str) -> bool {
self.to_string() == other.to_uppercase()
}
}
#[cfg(test)]
impl From<[u8; $size]> for $name {
fn from(value: [u8; $size]) -> Self {
Self(value)
}
}
};
}
impl_hash_wrapper!(Sha1, tor_llcrypto::d::Sha1, 20);
impl_hash_wrapper!(Sha256, tor_llcrypto::d::Sha256, 32);
impl_hash_wrapper!(Sha3_256, tor_llcrypto::d::Sha3_256, 32);
pub(crate) type DocumentId = Sha256;
#[derive(Debug, Clone, Copy, PartialEq, strum::EnumString, strum::Display, strum::EnumIter)]
#[strum(serialize_all = "kebab-case", ascii_case_insensitive)]
pub(crate) enum ContentEncoding {
Identity,
Deflate,
Gzip,
XZstd,
XTorLzma,
}
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
pub(crate) struct Timestamp(SystemTime);
impl From<SystemTime> for Timestamp {
fn from(value: SystemTime) -> Self {
Self(value)
}
}
impl From<Timestamp> for SystemTime {
fn from(value: Timestamp) -> Self {
value.0
}
}
impl Add<Duration> for Timestamp {
type Output = Self;
fn add(self, rhs: Duration) -> Self::Output {
Self(self.0.saturating_add(rhs))
}
}
impl Sub<Duration> for Timestamp {
type Output = Self;
fn sub(self, rhs: Duration) -> Self::Output {
Self(self.0.saturating_sub(rhs))
}
}
impl Sub<Timestamp> for Timestamp {
type Output = Duration;
fn sub(self, rhs: Timestamp) -> Self::Output {
#[allow(unstable_name_collisions)]
self.0.saturating_duration_since(rhs.0)
}
}
impl FromSql for Timestamp {
fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
let mut res = SystemTime::UNIX_EPOCH;
res = res.saturating_add(Duration::from_secs(value.as_i64()?.try_into().unwrap_or(0)));
Ok(Self(res))
}
}
impl ToSql for Timestamp {
fn to_sql(&self) -> rusqlite::Result<ToSqlOutput<'_>> {
#[allow(unstable_name_collisions)]
Ok(ToSqlOutput::from(
self.0
.saturating_duration_since(SystemTime::UNIX_EPOCH)
.as_secs()
.try_into()
.unwrap_or(i64::MAX),
))
}
}
#[derive(Educe)]
#[educe(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct ConsensusMeta<T> {
pub docid: DocumentId,
pub unsigned_sha3_256: Sha3_256,
pub valid_after: Timestamp,
pub fresh_until: Timestamp,
pub valid_until: Timestamp,
flavor: PhantomData<T>,
}
impl<T: FlavoredConsensusUnverified> ConsensusMeta<T> {
pub(crate) fn query(
tx: &Transaction,
tolerance: &DirTolerance,
now: Option<Timestamp>,
) -> Result<Vec<Self>, DatabaseError> {
let mut meta_stmt = tx.prepare_cached(sql!(
"
SELECT docid, unsigned_sha3_256, valid_after, fresh_until, valid_until
FROM consensus
WHERE
flavor = :flavor
AND
(
(:now IS NULL)
OR
(:now >= valid_after - :pre_valid AND :now <= valid_until + :post_valid)
)
ORDER BY valid_after DESC
"
))?;
let rows = meta_stmt.query_map(named_params! {
":flavor": T::flavor().name(),
":now": now,
":pre_valid": tolerance.pre_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
":post_valid": tolerance.post_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
}, |row| {
Ok(Self {
docid: row.get(0)?,
unsigned_sha3_256: row.get(1)?,
valid_after: row.get(2)?,
fresh_until: row.get(3)?,
valid_until: row.get(4)?,
flavor: Default::default(),
})
})?;
Ok(rows.collect::<Result<Vec<_>, _>>()?)
}
pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
SELECT content
FROM store
WHERE docid = :docid
"
))?;
let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
row.get::<_, Vec<u8>>(0)
})?;
let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
Ok(raw)
}
pub(crate) fn lifetime<R: Rng>(&self, rng: &mut R) -> Timestamp {
assert!(self.fresh_until < self.valid_until);
let offset = rng
.gen_range_checked(0..=((self.valid_until - self.fresh_until).as_secs() / 2))
.expect("invalid range?");
self.fresh_until + Duration::from_secs(offset)
}
pub(crate) fn missing_servers(
&self,
tx: &Transaction<'_>,
) -> Result<HashSet<Sha1>, DatabaseError> {
if T::flavor() != ConsensusFlavor::Plain {
return Ok(HashSet::new());
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT cr.unsigned_sha1
FROM consensus_router_descriptor_member AS cr
LEFT JOIN router_descriptor AS server ON cr.unsigned_sha1 = server.unsigned_sha1
WHERE
cr.consensus_docid = :docid
AND cr.unsigned_sha1 IS NOT NULL
AND server.unsigned_sha1 IS NULL
"
))?;
let missing = stmt
.query_map(named_params! {":docid": self.docid}, |row| row.get(0))?
.collect::<Result<HashSet<_>, _>>()?;
Ok(missing)
}
pub(crate) fn missing_extras(
&self,
tx: &Transaction<'_>,
) -> Result<HashSet<Sha1>, DatabaseError> {
if T::flavor() != ConsensusFlavor::Plain {
return Ok(HashSet::new());
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT server.extra_unsigned_sha1
FROM consensus_router_descriptor_member AS cr
INNER JOIN router_descriptor AS server ON cr.unsigned_sha1 = server.unsigned_sha1
LEFT JOIN router_extra_info AS extra ON server.extra_unsigned_sha1 = extra.unsigned_sha1
WHERE
cr.consensus_docid = :docid
AND server.extra_unsigned_sha1 IS NOT NULL
AND extra.unsigned_sha1 IS NULL
"
))?;
let missing = stmt
.query_map(named_params! {":docid": self.docid}, |row| row.get(0))?
.collect::<Result<HashSet<_>, _>>()?;
Ok(missing)
}
pub(crate) fn missing_micros(
&self,
tx: &Transaction<'_>,
) -> Result<HashSet<Sha256>, DatabaseError> {
if T::flavor() != ConsensusFlavor::Microdesc {
return Ok(HashSet::new());
}
let mut stmt = tx.prepare_cached(sql!(
"
SELECT cr.unsigned_sha2
FROM consensus_router_descriptor_member AS cr
LEFT JOIN router_descriptor AS micro ON cr.unsigned_sha2 = micro.unsigned_sha2
WHERE
cr.consensus_docid = :docid
AND cr.unsigned_sha2 IS NOT NULL
AND micro.unsigned_sha2 IS NULL
"
))?;
let missing = stmt
.query_map(named_params! {":docid": self.docid}, |row| row.get(0))?
.collect::<Result<HashSet<_>, _>>()?;
Ok(missing)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct AuthCertMeta {
pub docid: DocumentId,
pub kp_auth_id_rsa_sha1: Sha1,
pub kp_auth_sign_rsa_sha1: Sha1,
pub dir_key_published: Timestamp,
pub dir_key_expires: Timestamp,
}
impl AuthCertMeta {
pub(crate) fn query(
tx: &Transaction,
signatories: &[AuthCertKeyIds],
tolerance: &DirTolerance,
now: Timestamp,
) -> Result<(Vec<Self>, Vec<AuthCertKeyIds>), DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
SELECT docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1,
dir_key_published, dir_key_expires
FROM authority_key_certificate
WHERE
(:id_rsa, :sk_rsa) = (kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1)
AND :now >= dir_key_published - :pre_tolerance
AND :now <= dir_key_expires + :post_tolerance
ORDER BY dir_key_published DESC
LIMIT 1
"
))?;
let mut found = Vec::new();
let mut missing = Vec::new();
for kp in signatories {
let res = stmt
.query_one(
named_params! {
":id_rsa": kp.id_fingerprint.as_hex_upper(),
":sk_rsa": kp.sk_fingerprint.as_hex_upper(),
":now": now,
":pre_tolerance": tolerance.pre_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
":post_tolerance": tolerance.post_valid_tolerance().as_secs().try_into().unwrap_or(i64::MAX),
},
|row| Ok(Self {
docid: row.get(0)?,
kp_auth_id_rsa_sha1: row.get(1)?,
kp_auth_sign_rsa_sha1: row.get(2)?,
dir_key_published: row.get(3)?,
dir_key_expires: row.get(4)?,
})
)
.optional()?;
match res {
Some(cert) => found.push(cert),
None => missing.push(*kp),
}
}
Ok((found, missing))
}
pub(crate) fn data(&self, tx: &Transaction<'_>) -> Result<String, DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
SELECT content
FROM store
WHERE docid = :docid
"
))?;
let raw = stmt.query_one(named_params! {":docid": self.docid}, |row| {
row.get::<_, Vec<u8>>(0)
})?;
let raw = String::from_utf8(raw).map_err(into_internal!("utf-8 constraint violated?"))?;
Ok(raw)
}
pub(crate) fn insert<I: Iterator<Item = ContentEncoding>>(
tx: &Transaction<'_>,
encodings: I,
cert: &AuthCert,
data: &str,
) -> Result<(), DatabaseError> {
let mut stmt = tx.prepare_cached(sql!(
"
INSERT INTO authority_key_certificate
(docid, kp_auth_id_rsa_sha1, kp_auth_sign_rsa_sha1, dir_key_published, dir_key_expires)
VALUES
(:docid, :id_rsa, :sign_rsa, :published, :expires)
ON CONFLICT DO NOTHING
"
))?;
let docid = store_insert(tx, data.as_bytes(), encodings)?;
stmt.execute(named_params! {
":docid": docid,
":id_rsa": cert.dir_identity_key.to_rsa_identity().as_hex_upper(),
":sign_rsa": cert.dir_signing_key.to_rsa_identity().as_hex_upper(),
":published": Timestamp::from(cert.dir_key_published.0),
":expires": Timestamp::from(cert.dir_key_expires.0),
})?;
Ok(())
}
}
macro_rules! sql {
($s:literal) => {
$s
};
}
pub(crate) use sql;
pub(crate) fn open<P: AsRef<Path>>(
path: P,
) -> Result<Pool<SqliteConnectionManager>, DatabaseError> {
let num_cores = std::thread::available_parallelism()
.unwrap_or(NonZero::new(8).expect("8 == 0?"))
.get() as u32;
let manager = r2d2_sqlite::SqliteConnectionManager::file(&path);
let pool = Pool::builder().max_size(num_cores).build(manager)?;
rw_tx(&pool, |tx| {
let has_arti_dirserver_schema_version = match tx.query_one(
sql!(
"
SELECT name
FROM sqlite_master
WHERE type = 'table'
AND name = 'arti_dirserver_schema_version'
"
),
params![],
|_| Ok(()),
) {
Ok(()) => true,
Err(rusqlite::Error::QueryReturnedNoRows) => false,
Err(e) => return Err(DatabaseError::LowLevel(e)),
};
if has_arti_dirserver_schema_version {
let version = tx.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version WHERE rowid = 1"),
params![],
|row| row.get::<_, String>(0),
)?;
match version.as_ref() {
"1" => {}
unknown => {
return Err(DatabaseError::IncompatibleSchema {
version: unknown.into(),
});
}
}
} else {
tx.execute_batch(V1_SCHEMA)?;
}
Ok::<_, DatabaseError>(())
})??;
Ok(pool)
}
pub(crate) fn read_tx<U, F>(pool: &Pool<SqliteConnectionManager>, op: F) -> Result<U, DatabaseError>
where
F: FnOnce(&Transaction<'_>) -> U,
{
let mut conn = pool.get()?;
conn.execute_batch(GLOBAL_OPTIONS)?;
let tx = conn.transaction_with_behavior(TransactionBehavior::Deferred)?;
let res = op(&tx);
tx.rollback()?;
Ok(res)
}
pub(crate) fn rw_tx<U, F>(pool: &Pool<SqliteConnectionManager>, op: F) -> Result<U, DatabaseError>
where
F: FnOnce(&Transaction<'_>) -> U,
{
let mut conn = pool.get()?;
conn.execute_batch(GLOBAL_OPTIONS)?;
let tx = conn.transaction_with_behavior(TransactionBehavior::Exclusive)?;
let res = op(&tx);
tx.commit()?;
Ok(res)
}
pub(crate) fn store_insert<I: Iterator<Item = ContentEncoding>>(
tx: &Transaction,
data: &[u8],
encodings: I,
) -> Result<DocumentId, DatabaseError> {
let mut store_stmt = tx.prepare_cached(sql!(
"
INSERT INTO store (docid, content)
VALUES
(:docid, :content)
ON CONFLICT DO NOTHING
"
))?;
let mut compressed_stmt = tx.prepare_cached(sql!(
"
INSERT INTO compressed_document (algorithm, identity_docid, compressed_docid)
VALUES
(:algorithm, :identity_docid, :compressed_docid)
ON CONFLICT DO NOTHING
"
))?;
let identity_docid = DocumentId::digest(data);
store_stmt.execute(named_params! {
":docid": identity_docid,
":content": data
})?;
for encoding in encodings {
if encoding == ContentEncoding::Identity {
continue;
}
let compressed = compress(data, encoding).map_err(into_internal!("{encoding} failed?"))?;
let compressed_docid = DocumentId::digest(&compressed);
store_stmt.execute(named_params! {
":docid": compressed_docid,
":content": compressed,
})?;
compressed_stmt.execute(named_params! {
":algorithm": encoding.to_string(),
":identity_docid": identity_docid,
":compressed_docid": compressed_docid,
})?;
}
Ok(identity_docid)
}
fn compress(data: &[u8], encoding: ContentEncoding) -> Result<Vec<u8>, std::io::Error> {
match encoding {
ContentEncoding::Identity => Ok(data.to_vec()),
ContentEncoding::Deflate => {
let mut w = DeflateEncoder::new(Vec::new(), Default::default());
w.write_all(data)?;
w.finish()
}
ContentEncoding::Gzip => {
let mut w = GzEncoder::new(Vec::new(), Default::default());
w.write_all(data)?;
w.finish()
}
ContentEncoding::XZstd => zstd::encode_all(data, Default::default()),
ContentEncoding::XTorLzma => {
let mut res = Vec::new();
lzma_rs::lzma_compress(&mut Cursor::new(data), &mut res)?;
Ok(res)
}
}
}
#[cfg(test)]
mod test {
#![allow(clippy::bool_assert_comparison)]
#![allow(clippy::clone_on_copy)]
#![allow(clippy::dbg_macro)]
#![allow(clippy::mixed_attributes_style)]
#![allow(clippy::print_stderr)]
#![allow(clippy::print_stdout)]
#![allow(clippy::single_char_pattern)]
#![allow(clippy::unwrap_used)]
#![allow(clippy::unchecked_time_subtraction)]
#![allow(clippy::useless_vec)]
#![allow(clippy::needless_pass_by_value)]
#![allow(clippy::string_slice)] use std::{
collections::HashSet,
io::Read,
sync::{Arc, Once},
};
use flate2::read::{DeflateDecoder, GzDecoder};
use rusqlite::Connection;
use strum::IntoEnumIterator;
use tempfile::tempdir;
use tor_basic_utils::test_rng::testing_rng;
use tor_dircommon::config::DirToleranceBuilder;
use tor_llcrypto::pk::rsa::RsaIdentity;
use tor_netdoc::doc::netstatus::{md, plain};
use crate::testdata2;
use super::*;
type Plain = plain::NetworkStatusUnverified;
type Md = md::NetworkStatusUnverified;
#[test]
fn open_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
open(&db_path).unwrap();
let conn = Connection::open(&db_path).unwrap();
let version = conn
.query_one(
"SELECT version FROM arti_dirserver_schema_version WHERE rowid = 1",
params![],
|row| row.get::<_, String>(0),
)
.unwrap();
assert_eq!(version, "1");
conn.execute(
"UPDATE arti_dirserver_schema_version SET version = 42",
params![],
)
.unwrap();
drop(conn);
assert_eq!(
open(&db_path).unwrap_err().to_string(),
"incompatible schema version: 42"
);
}
#[test]
fn read_tx_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(&db_path).unwrap();
read_tx(&pool, |tx| {
tx.execute_batch("DELETE FROM arti_dirserver_schema_version")
.unwrap();
let e = tx
.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version"),
params![],
|row| row.get::<_, String>(0),
)
.unwrap_err();
assert_eq!(e, rusqlite::Error::QueryReturnedNoRows);
})
.unwrap();
let version: String = read_tx(&pool, |tx| {
tx.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version"),
params![],
|row| row.get(0),
)
.unwrap()
})
.unwrap();
assert_eq!(version, "1");
}
#[test]
fn rw_tx_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(&db_path).unwrap();
rw_tx(&pool, |tx| {
tx.execute_batch("DELETE FROM arti_dirserver_schema_version")
.unwrap();
})
.unwrap();
read_tx(&pool, |tx| {
let e = tx
.query_one(
sql!("SELECT version FROM arti_dirserver_schema_version"),
params![],
|row| row.get::<_, String>(0),
)
.unwrap_err();
assert_eq!(e, rusqlite::Error::QueryReturnedNoRows);
})
.unwrap();
}
#[test]
fn rw_tx_busy_timeout_working() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(db_path).unwrap();
let t1_acquired_lock = Arc::new(Once::new());
let t2_is_waiting = Arc::new(Once::new());
let t1 = std::thread::spawn({
let pool = pool.clone();
let t1_acquired_lock = t1_acquired_lock.clone();
let t2_is_waiting = t2_is_waiting.clone();
move || {
rw_tx(&pool, move |_tx| {
t1_acquired_lock.call_once(|| ());
println!("t1 acquired write lock");
t2_is_waiting.wait();
})
.unwrap();
println!("t2 released write lock");
}
});
println!("t2 waits for t1 to acquire write lock");
t1_acquired_lock.wait();
t2_is_waiting.call_once(|| ());
rw_tx(&pool, |_| ()).unwrap();
println!("t2 acquired and released write lock");
t1.join().unwrap();
}
#[test]
fn rw_tx_busy_timeout_busy() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
let pool = open(db_path).unwrap();
let t1_acquired_lock = Arc::new(Once::new());
let t2_gave_up = Arc::new(Once::new());
let t1 = std::thread::spawn({
let pool = pool.clone();
let t1_acquired_lock = t1_acquired_lock.clone();
let t2_gave_up = t2_gave_up.clone();
move || {
rw_tx(&pool, move |_tx| {
t1_acquired_lock.call_once(|| ());
println!("t1 acquired write lock");
t2_gave_up.wait();
})
.unwrap();
println!("t1 released write lock");
}
});
println!("t2 waits for t1 to acquire write lock");
t1_acquired_lock.wait();
let e = rw_tx(&pool, |_| ()).unwrap_err();
assert_eq!(
e.to_string(),
"low-level rusqlite error: database is locked"
);
println!("t2 gave up on acquiring write lock");
t2_gave_up.call_once(|| ());
t1.join().unwrap();
}
#[test]
fn store_insert_test() {
let db_dir = tempdir().unwrap();
let db_path = db_dir.path().join("db");
open(&db_path).unwrap();
let mut conn = Connection::open(&db_path).unwrap();
let tx = conn.transaction().unwrap();
let docid = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
assert_eq!(
docid,
"C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2"
);
let res = tx
.query_one(
sql!(
"
SELECT content
FROM store
WHERE docid = 'C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2'
"
),
params![],
|row| row.get::<_, Vec<u8>>(0),
)
.unwrap();
assert_eq!(res, "foobar".as_bytes());
let mut stmt = tx.prepare_cached(sql!(
"
SELECT algorithm
FROM compressed_document
WHERE identity_docid = 'C3AB8FF13720E8AD9047DD39466B3C8974E592C2FA383D4A3960714CAEF0C4F2'
"
)).unwrap();
let algorithms = stmt
.query_map(params![], |row| row.get::<_, String>(0))
.unwrap();
let algorithms = algorithms.map(|x| x.unwrap()).collect::<HashSet<_>>();
assert_eq!(
algorithms,
HashSet::from([
"deflate".to_string(),
"gzip".to_string(),
"x-zstd".to_string(),
"x-tor-lzma".to_string()
])
);
let docid_second = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
assert_eq!(docid, docid_second);
let n = tx
.execute(
sql!(
"
DELETE FROM
compressed_document
WHERE algorithm IN ('deflate', 'x-zstd')
"
),
params![],
)
.unwrap();
assert_eq!(n, 2);
let docid_third = store_insert(&tx, "foobar".as_bytes(), ContentEncoding::iter()).unwrap();
assert_eq!(docid, docid_third);
let algorithms = stmt
.query_map(params![], |row| row.get::<_, String>(0))
.unwrap();
let algorithms = algorithms.map(|x| x.unwrap()).collect::<HashSet<_>>();
assert_eq!(
algorithms,
HashSet::from([
"deflate".to_string(),
"gzip".to_string(),
"x-zstd".to_string(),
"x-tor-lzma".to_string()
])
);
}
#[test]
fn compress_test() {
fn contains(encoding: ContentEncoding, res: &[(ContentEncoding, Vec<u8>)]) {
assert!(res.iter().any(|x| x.0 == encoding));
}
const INPUT: &[u8] = "foobar".as_bytes();
let res = ContentEncoding::iter()
.map(|encoding| (encoding, compress(INPUT, encoding).unwrap()))
.collect::<Vec<_>>();
assert_eq!(res.len(), 5);
contains(ContentEncoding::Identity, &res);
contains(ContentEncoding::Deflate, &res);
contains(ContentEncoding::Gzip, &res);
contains(ContentEncoding::XTorLzma, &res);
contains(ContentEncoding::XZstd, &res);
for (encoding, compressed) in res {
let mut decompressed = Vec::new();
match encoding {
ContentEncoding::Identity => decompressed = compressed,
ContentEncoding::Deflate => {
DeflateDecoder::new(Cursor::new(compressed))
.read_to_end(&mut decompressed)
.unwrap();
}
ContentEncoding::Gzip => {
GzDecoder::new(Cursor::new(compressed))
.read_to_end(&mut decompressed)
.unwrap();
}
ContentEncoding::XTorLzma => {
lzma_rs::lzma_decompress(&mut Cursor::new(compressed), &mut decompressed)
.unwrap();
}
ContentEncoding::XZstd => {
decompressed = zstd::decode_all(Cursor::new(compressed)).unwrap();
}
}
assert_eq!(decompressed, INPUT);
}
}
#[test]
fn recent_consensus() {
let pool = testdata2::test_db();
let no_tolerance = DirToleranceBuilder::default()
.pre_valid_tolerance(Duration::ZERO)
.post_valid_tolerance(Duration::ZERO)
.build()
.unwrap();
let liberal_tolerance = DirToleranceBuilder::default()
.pre_valid_tolerance(Duration::from_secs(60 * 60)) .post_valid_tolerance(Duration::from_secs(60 * 60)) .build()
.unwrap();
let docid = Sha256::digest(testdata2::current_consensus_ns().1.as_bytes());
let lifetime = testdata2::current_consensus_ns().0.preamble.lifetime;
let unsigned_sha3_256 = testdata2::consensus_sha3(testdata2::current_consensus_ns().1);
read_tx(&pool, move |tx| {
assert!(
ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some((lifetime.valid_after.0 - Duration::from_secs(60 * 60 * 24 * 365)).into())
)
.unwrap()
.is_empty()
);
assert!(
ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some((lifetime.valid_until.0 + Duration::from_secs(60 * 60 * 24 * 365)).into()),
)
.unwrap()
.is_empty()
);
assert!(
ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some((lifetime.valid_after.0 - Duration::from_secs(1)).into()),
)
.unwrap()
.is_empty()
);
assert!(
ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some((lifetime.valid_until.0 + Duration::from_secs(1)).into()),
)
.unwrap()
.is_empty()
);
let res1 = ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some(lifetime.valid_after.0.into()),
)
.unwrap()[0];
let res2 = ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some(lifetime.valid_until.0.into()),
)
.unwrap()[0];
let res3 = ConsensusMeta::<Plain>::query(
tx,
&no_tolerance,
Some(testdata2::valid_system_time().into()),
)
.unwrap()[0];
let res4 = ConsensusMeta::<Plain>::query(tx, &no_tolerance, None).unwrap()[0];
assert_eq!(
res1,
ConsensusMeta {
docid,
unsigned_sha3_256,
valid_after: lifetime.valid_after.0.into(),
fresh_until: lifetime.fresh_until.0.into(),
valid_until: lifetime.valid_until.0.into(),
flavor: Default::default(),
}
);
assert_eq!(res1, res2);
assert_eq!(res2, res3);
assert_eq!(res3, res4);
let res1 = ConsensusMeta::<Plain>::query(
tx,
&liberal_tolerance,
Some((lifetime.valid_after.0 - Duration::from_secs(60 * 30)).into()),
)
.unwrap()[0];
let res2 = ConsensusMeta::<Plain>::query(
tx,
&liberal_tolerance,
Some((lifetime.valid_until.0 + Duration::from_secs(60 * 30)).into()),
)
.unwrap()[0];
assert_eq!(
res1,
ConsensusMeta {
docid,
unsigned_sha3_256,
valid_after: lifetime.valid_after.0.into(),
fresh_until: lifetime.fresh_until.0.into(),
valid_until: lifetime.valid_until.0.into(),
flavor: Default::default(),
}
);
assert_eq!(res1, res2);
})
.unwrap();
}
#[test]
fn sync_timeout() {
let docid = Sha256::digest(testdata2::current_consensus_ns().1.as_bytes());
let lifetime = testdata2::current_consensus_ns().0.preamble.lifetime;
let unsigned_sha3_256 = testdata2::consensus_sha3(testdata2::current_consensus_ns().1);
let cons = ConsensusMeta::<Plain> {
docid,
unsigned_sha3_256,
valid_after: lifetime.valid_after.0.into(),
fresh_until: lifetime.fresh_until.0.into(),
valid_until: lifetime.valid_until.0.into(),
flavor: Default::default(),
};
for _ in 0..10000 {
let when = cons.lifetime(&mut testing_rng());
assert!(when >= lifetime.fresh_until.0.into());
assert!(
when <= (lifetime.fresh_until.0
+ (lifetime
.valid_until
.0
.duration_since(lifetime.fresh_until.0)
.unwrap()
/ 2))
.into()
);
}
}
#[test]
fn get_auth_cert() {
let pool = testdata2::test_db();
let (found, missing) = read_tx(&pool, |tx| {
AuthCertMeta::query(
tx,
&[],
&DirTolerance::default(),
testdata2::valid_system_time().into(),
)
})
.unwrap()
.unwrap();
assert!(found.is_empty());
assert!(missing.is_empty());
let (found, missing) = read_tx(&pool, |tx| {
AuthCertMeta::query(
tx,
&[
AuthCertKeyIds {
id_fingerprint: *testdata2::current_auth_certs()[0].0.id_fingerprint(),
sk_fingerprint: testdata2::current_auth_certs()[0]
.0
.signing_key()
.to_rsa_identity(),
},
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
},
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
},
],
&DirTolerance::default(),
testdata2::valid_system_time().into(),
)
})
.unwrap()
.unwrap();
assert_eq!(
found,
vec![AuthCertMeta {
docid: DocumentId::digest(testdata2::current_auth_certs()[0].1.as_bytes()),
kp_auth_id_rsa_sha1: Sha1::from(
testdata2::current_auth_certs()[0]
.0
.id_fingerprint()
.to_bytes()
),
kp_auth_sign_rsa_sha1: Sha1::from(
testdata2::current_auth_certs()[0]
.0
.signing_key()
.to_rsa_identity()
.to_bytes()
),
dir_key_published: testdata2::current_auth_certs()[0].0.published().into(),
dir_key_expires: testdata2::current_auth_certs()[0].0.expires().into(),
}]
);
assert_eq!(
missing,
vec![
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
},
AuthCertKeyIds {
id_fingerprint: RsaIdentity::from_hex(
"FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF",
)
.unwrap(),
sk_fingerprint: RsaIdentity::from_hex(
"0000000000000000000000000000000000000000",
)
.unwrap(),
}
]
);
}
#[test]
fn missing_server_descriptors() {
let pool = testdata2::test_db();
let meta = read_tx(&pool, |tx| {
ConsensusMeta::<Plain>::query(
tx,
&DirTolerance::default(),
Some(testdata2::valid_system_time().into()),
)
})
.unwrap()
.unwrap()[0];
assert_eq!(
meta.docid,
DocumentId::digest(testdata2::current_consensus_ns().1.as_bytes())
);
let removed_descriptor = *testdata2::current_consensus_ns().0.routers[0].doc_digest();
let removed_descriptor = Sha1::from(removed_descriptor);
pool.get()
.unwrap()
.execute(
sql!(
"
DELETE FROM router_descriptor
WHERE unsigned_sha1 = ?1
"
),
params![removed_descriptor],
)
.unwrap();
let missing_servers = read_tx(&pool, |tx| meta.missing_servers(tx))
.unwrap()
.unwrap();
assert_eq!(missing_servers, HashSet::from([removed_descriptor]));
rw_tx(&pool, |tx| {
tx.execute(sql!("DELETE FROM router_descriptor"), params![])
})
.unwrap()
.unwrap();
let missing_servers = read_tx(&pool, |tx| meta.missing_servers(tx))
.unwrap()
.unwrap();
let all_descriptors = testdata2::current_router_descs()
.iter()
.map(|x| Sha1::from(x.1.hashes.sha1.unwrap()))
.collect::<HashSet<_>>();
assert!(
missing_servers
.iter()
.all(|sha1| all_descriptors.contains(sha1))
);
}
#[test]
fn missing_extra_infos() {
let pool = testdata2::test_db();
let meta = read_tx(&pool, |tx| {
ConsensusMeta::<Plain>::query(
tx,
&DirTolerance::default(),
Some(testdata2::valid_system_time().into()),
)
})
.unwrap()
.unwrap()[0];
assert_eq!(
meta.docid,
DocumentId::digest(testdata2::current_consensus_ns().1.as_bytes())
);
let missing_extras = read_tx(&pool, |tx| meta.missing_extras(tx))
.unwrap()
.unwrap();
assert!(missing_extras.is_empty());
}
#[test]
fn missing_micro_descriptors() {
let pool = testdata2::test_db();
let meta = read_tx(&pool, |tx| {
ConsensusMeta::<Md>::query(
tx,
&DirTolerance::default(),
Some(testdata2::valid_system_time().into()),
)
})
.unwrap()
.unwrap()[0];
assert_eq!(
meta.docid,
DocumentId::digest(testdata2::current_consensus_md().1.as_bytes())
);
let removed_descriptor = *testdata2::current_consensus_md().0.routers[0].doc_digest();
let removed_descriptor = Sha256::from(removed_descriptor);
pool.get()
.unwrap()
.execute(
sql!(
"
DELETE FROM router_descriptor
WHERE unsigned_sha2 = ?1
"
),
params![removed_descriptor],
)
.unwrap();
let missing_micros = read_tx(&pool, |tx| meta.missing_micros(tx))
.unwrap()
.unwrap();
assert_eq!(missing_micros, HashSet::from([removed_descriptor]));
rw_tx(&pool, |tx| {
tx.execute(sql!("DELETE FROM router_descriptor"), params![])
})
.unwrap()
.unwrap();
let missing_micros = read_tx(&pool, |tx| meta.missing_micros(tx))
.unwrap()
.unwrap();
let all_descriptors = testdata2::current_micro_descs()
.iter()
.map(|x| Sha256::digest(x.1.as_bytes()))
.collect::<HashSet<_>>();
assert!(
missing_micros
.iter()
.all(|sha2| all_descriptors.contains(sha2))
);
}
}