use std::{collections::VecDeque, marker::PhantomData, mem, net::SocketAddr, time::Duration};
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rand::Rng;
use rusqlite::Transaction;
use strum::IntoEnumIterator;
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tor_checkable::TimeBound;
use tor_dirclient::request::{AuthCertRequest, ConsensusRequest, Requestable};
use tor_dircommon::{authority::AuthorityContacts, config::DirTolerance};
use tor_error::internal;
use tor_netdoc::{
doc::{
authcert::{AuthCert, AuthCertKeyIds, AuthCertUnverified},
netstatus::ConsensusVerifiabilityError,
},
parse2::{self, NetdocParseable, NetdocParseableUnverified, ParseInput, VerifyFailed},
};
use tor_rtcompat::PreferredRuntime;
use tracing::debug;
use crate::{
database::{self as db, AuthCertMeta, ConsensusMeta, ContentEncoding, Timestamp},
err::{AuthorityRequestError, DatabaseError, OperationError},
types::FlavoredConsensusUnverified,
};
mod poc;
const UNVERIFIED_TTL: Duration = Duration::from_mins(10);
#[derive(Debug, Clone, Copy, PartialEq, Eq, strum::Display)]
enum State {
LoadConsensus,
FetchConsensus,
AuthCerts,
StoreConsensus,
Descriptors,
Hibernate,
}
#[derive(Debug)]
struct StaticEngine<T> {
authorities: AuthorityContacts,
tolerance: DirTolerance,
rt: PreferredRuntime,
_phantom: PhantomData<T>,
}
#[derive(Debug, Clone)]
enum ConsensusBoundData<T: FlavoredConsensusUnverified> {
None,
Unverified {
consensus: T,
raw: String,
ttl: Timestamp,
},
Verified {
consensus: ConsensusMeta<T>,
ttl: Timestamp,
},
}
impl<T: FlavoredConsensusUnverified> StaticEngine<T> {
fn determine_state(
&self,
tx: &Transaction<'_>,
data: &ConsensusBoundData<T>,
now: Timestamp,
) -> Result<State, DatabaseError> {
let state = match data {
ConsensusBoundData::None => {
match self.recent_consensus(tx, now)? {
Some(_) => State::LoadConsensus,
None => State::FetchConsensus,
}
}
ConsensusBoundData::Unverified { consensus, ttl, .. } if now < *ttl => {
let certs_already = self.certs_already(tx, now)?;
match consensus.can_verify(self.authorities.v3idents(), &certs_already) {
Ok(()) => State::StoreConsensus,
Err(ConsensusVerifiabilityError::InsufficientTrustedSigners) => {
State::Hibernate
}
Err(ConsensusVerifiabilityError::MissingAuthCerts { .. }) => State::AuthCerts,
}
}
ConsensusBoundData::Unverified { .. } => State::FetchConsensus,
ConsensusBoundData::Verified { consensus, ttl, .. } => {
if *ttl <= now {
State::FetchConsensus
} else if consensus.missing_routers(tx, Some(1))?.is_empty()
&& consensus.missing_micros(tx, Some(1))?.is_empty()
&& consensus.missing_extras(tx, Some(1))?.is_empty()
{
State::Hibernate
} else {
State::Descriptors
}
}
};
Ok(state)
}
async fn execute<R: Rng>(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &[SocketAddr],
now: Timestamp,
rng: &mut R,
) -> Result<(), OperationError> {
let state = db::read_tx(pool, |tx| self.determine_state(tx, data, now))??;
debug!("state is {state}");
match state {
State::LoadConsensus => self.load_consensus(pool, data, now, rng),
State::FetchConsensus => Ok(self.fetch_consensus(data, endpoint, now).await?),
State::AuthCerts => self.auth_certs(pool, data, endpoint, now).await,
State::StoreConsensus => self.store_consensus(pool, data, now),
State::Descriptors => todo!(),
State::Hibernate => self.hibernate(data, now).await,
}
}
fn load_consensus<R: Rng>(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
now: Timestamp,
rng: &mut R,
) -> Result<(), OperationError> {
let consensus = db::read_tx(pool, |tx| self.recent_consensus(tx, now))??
.ok_or(internal!("database externally modified?"))?;
let ttl = consensus.ttl(rng);
*data = ConsensusBoundData::Verified { consensus, ttl };
Ok(())
}
#[allow(clippy::string_slice)] async fn fetch_consensus(
&self,
data: &mut ConsensusBoundData<T>,
endpoint: &[SocketAddr],
now: Timestamp,
) -> Result<(), AuthorityRequestError> {
let (raw, consensus) = self
.send_request(endpoint, ConsensusRequest::new(T::flavor()))
.await?;
let mut consensus = consensus
.into_iter()
.map(|(doc, start, end)| (raw[start..end].to_owned(), doc))
.collect::<VecDeque<_>>();
if consensus.len() != 1 {
return Err(AuthorityRequestError::Response(
"invalid number of consensus?",
));
}
let (raw, consensus) = consensus.pop_front().expect("pop_front");
let ttl = now + UNVERIFIED_TTL;
*data = ConsensusBoundData::Unverified {
consensus,
raw,
ttl,
};
Ok(())
}
#[allow(clippy::string_slice)] async fn auth_certs(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &[SocketAddr],
now: Timestamp,
) -> Result<(), OperationError> {
let certs_already = db::read_tx(pool, |tx| self.certs_already(tx, now))??;
let missing = match data {
ConsensusBoundData::Unverified { consensus, .. } => {
match consensus.can_verify(self.authorities.v3idents(), &certs_already) {
Err(ConsensusVerifiabilityError::MissingAuthCerts { missing, .. }) => missing,
_ => return Err(OperationError::Bug(internal!("we have all auth certs"))),
}
}
_ => return Err(OperationError::Bug(internal!("data is not unverified"))),
};
let mut requ = AuthCertRequest::new();
for kp in missing.iter().copied() {
requ.push(kp);
}
let (resp, certs) = self
.send_request::<_, AuthCertUnverified>(endpoint, requ)
.await?;
let certs = certs
.into_iter()
.filter_map(|(unverified, start, end)| {
let kp = unverified.inspect_unverified().0.key_ids();
if !missing.contains(&kp) {
debug!("authority returned certificate we did not asked for: {kp:?}");
return None;
}
let verified = match unverified.verify(self.authorities.v3idents()) {
Ok(c) => c,
Err(e) => {
debug!("received invalid auth cert ({kp:?}): {e}");
return None;
}
};
let timely = match self
.tolerance
.extend_tolerance(verified)
.if_valid_at(&now.into())
{
Ok(c) => c,
Err(e) => {
debug!("received non-timely auth cert ({kp:?}): {e}");
return None;
}
};
Some((timely, &resp[start..end]))
})
.collect::<Vec<_>>();
if certs.is_empty() {
Err(Box::new(AuthorityRequestError::Response(
"response lead to no progress",
)))?;
}
db::rw_tx(pool, |tx| {
for (cert, data) in certs {
AuthCertMeta::insert(tx, ContentEncoding::iter(), &cert, data)?;
}
Ok::<_, DatabaseError>(())
})??;
Ok(())
}
fn store_consensus(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
now: Timestamp,
) -> Result<(), OperationError> {
let (unverified, raw) = match mem::replace(data, ConsensusBoundData::None) {
ConsensusBoundData::Unverified { consensus, raw, .. } => (consensus, raw),
_ => return Err(OperationError::Bug(internal!("data is not unverified"))),
};
db::rw_tx(pool, |tx| {
let certs_already = self.certs_already(tx, now)?;
let (verified, sigs) = self.verify_consensus(unverified, &certs_already, now)?;
ConsensusMeta::<T>::insert(tx, ContentEncoding::iter(), (&verified, &sigs), &raw)?;
Ok::<_, OperationError>(())
})?
}
async fn hibernate(
&self,
data: &mut ConsensusBoundData<T>,
now: Timestamp,
) -> Result<(), OperationError> {
match data {
ConsensusBoundData::None => {
return Err(internal!("hibernating without a consensus?").into());
}
ConsensusBoundData::Verified { ttl, .. }
| ConsensusBoundData::Unverified { ttl, .. } => {
let timeout = *ttl - now;
debug!("hibernating for {}s", timeout.as_secs());
tokio::time::sleep(timeout).await;
}
}
Ok(())
}
async fn send_request<R: Requestable, D: NetdocParseable>(
&self,
endpoint: &[SocketAddr],
requ: R,
) -> Result<(String, Vec<(D, usize, usize)>), AuthorityRequestError> {
if endpoint.is_empty() {
return Err(AuthorityRequestError::Bug(internal!("empty endpoint?")));
}
let mut stream = TcpStream::connect(endpoint)
.await
.map_err(AuthorityRequestError::TcpConnect)?
.compat();
let resp = tor_dirclient::send_request(&self.rt, &requ, &mut stream, None)
.await
.map(|resp| resp.output_string().map(|resp| resp.to_owned()));
drop(stream);
let resp = match resp {
Ok(Ok(r)) => Ok(r),
Ok(Err(e)) => Err(e),
Err(tor_dirclient::Error::RequestFailed(e)) => Err(e),
Err(e) => {
return Err(AuthorityRequestError::Bug(internal!(
"unhandled dirclient error: {e}"
)));
}
}?;
let parsed = parse2::parse_netdoc_multiple_sophisticated(&ParseInput::new(&resp, ""))?
.into_iter()
.filter_map(|(res, start, end)| match res {
Ok(doc) => Some((doc, start, end)),
Err(e) => {
debug!("ignoring invalid netdoc: {e}");
None
}
})
.collect();
Ok((resp, parsed))
}
fn recent_consensus(
&self,
tx: &Transaction<'_>,
now: Timestamp,
) -> Result<Option<ConsensusMeta<T>>, DatabaseError> {
let meta = match ConsensusMeta::<T>::query(tx)?.as_slice() {
&[front] | &[front, ..] => front,
&[] => return Ok(None),
};
let raw = meta.data(tx)?;
let unverified = match parse2::parse_netdoc::<T>(&ParseInput::new(&raw, "<database>")) {
Ok(unverified) => unverified,
Err(e) => {
debug!("unparseable consensus in database: {meta:?} {e}");
return Ok(None);
}
};
let certs_already = self.certs_already(tx, now)?;
match self.verify_consensus(unverified, &certs_already, now) {
Ok(_) => Ok(Some(meta)),
Err(e) => {
debug!("ignoring invalid consensus in database: {meta:?} {e}");
Ok(None)
}
}
}
fn verify_consensus(
&self,
unverified: T,
certs_already: &[AuthCert],
now: Timestamp,
) -> Result<(T::Body, T::Signatures), VerifyFailed> {
let sigs = unverified.sigs().clone();
let verified = unverified.verify(self.authorities.v3idents(), certs_already)?;
self.tolerance
.extend_tolerance(verified)
.if_valid_at(&now.into())
.map(|body| (body, sigs))
.map_err(|e| e.into())
}
fn certs_already(
&self,
tx: &Transaction<'_>,
now: Timestamp,
) -> Result<Vec<AuthCert>, DatabaseError> {
let raw_certs = AuthCertMeta::query(tx)?
.into_iter()
.map(|meta| Ok::<_, DatabaseError>((meta, meta.data(tx)?)))
.collect::<Result<Vec<_>, _>>()?;
let mut certs_already = Vec::new();
for (meta, raw) in raw_certs {
let key_ids = AuthCertKeyIds {
id_fingerprint: meta.kp_auth_id_rsa_sha1.0.into(),
sk_fingerprint: meta.kp_auth_sign_rsa_sha1.0.into(),
};
let unverified = match parse2::parse_netdoc::<AuthCertUnverified>(&ParseInput::new(
&raw,
"<database>",
)) {
Ok(c) => c,
Err(e) => {
debug!("unparseable auth cert ({key_ids:?}) in database: {e}");
continue;
}
};
let verified = match unverified.verify(self.authorities.v3idents()) {
Ok(c) => c,
Err(e) => {
debug!("ignoring invalid auth cert ({key_ids:?}): {e}");
continue;
}
};
let timely = match self
.tolerance
.extend_tolerance(verified)
.if_valid_at(&now.into())
{
Ok(c) => c,
Err(e) => {
debug!("ignoring non-timely auth cert ({key_ids:?}): {e}");
continue;
}
};
certs_already.push(timely);
}
Ok(certs_already)
}
}
#[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;
use rusqlite::params;
use tokio::{
io::{AsyncReadExt, AsyncWriteExt},
net::TcpListener,
};
use tor_basic_utils::test_rng::testing_rng;
use crate::{database::sql, testdata2};
use super::*;
type Plain = tor_netdoc::doc::netstatus::plain::NetworkStatusUnverified;
type Md = tor_netdoc::doc::netstatus::md::NetworkStatusUnverified;
#[tokio::test]
async fn state_load_consensus() {
let pool = testdata2::test_db();
let mut data = ConsensusBoundData::<Plain>::None;
let engine = StaticEngine {
authorities: testdata2::current_auth_cert_contacts(),
tolerance: DirTolerance::default(),
rt: PreferredRuntime::current().unwrap(),
_phantom: Default::default(),
};
let time: Timestamp = testdata2::valid_system_time().into();
let fresh_until: Timestamp = testdata2::current_consensus_ns()
.0
.preamble
.lifetime
.fresh_until
.0
.into();
let valid_until: Timestamp = testdata2::current_consensus_ns()
.0
.preamble
.lifetime
.valid_until
.0
.into();
let fresh_until_half = fresh_until + ((valid_until - fresh_until) / 2);
let relay_to_remove = &testdata2::current_consensus_ns().0.routers[0];
let relay_to_remove = db::Sha1::from(*relay_to_remove.doc_digest());
pool.get()
.unwrap()
.execute(
sql!("DELETE FROM router_descriptor WHERE unsigned_sha1 = ?1"),
params![relay_to_remove],
)
.unwrap();
engine
.load_consensus(&pool, &mut data, time, &mut testing_rng())
.unwrap();
match data {
ConsensusBoundData::Verified { consensus, ttl, .. } => {
db::read_tx(&pool, |tx| {
assert_eq!(
consensus.missing_routers(tx, None).unwrap(),
HashSet::from([relay_to_remove])
);
assert!(consensus.missing_extras(tx, None).unwrap().is_empty());
assert!(consensus.missing_micros(tx, None).unwrap().is_empty());
})
.unwrap();
assert!(ttl >= fresh_until);
assert!(ttl <= fresh_until_half);
}
_ => panic!("data is not verified"),
}
}
#[tokio::test]
async fn state_fetch_consensus() {
let pool = testdata2::test_db();
let mut data = ConsensusBoundData::<Plain>::None;
let engine = StaticEngine {
authorities: testdata2::current_auth_cert_contacts(),
tolerance: DirTolerance::default(),
rt: PreferredRuntime::current().unwrap(),
_phantom: Default::default(),
};
let now = Timestamp::from(testdata2::invalid_system_time());
let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
.unwrap()
.unwrap();
assert_eq!(state, State::FetchConsensus);
let server = TcpListener::bind("[::1]:0").await.unwrap();
let saddr = server.local_addr().unwrap();
tokio::spawn(async move {
let (mut stream, _) = server.accept().await.unwrap();
let mut buf = vec![0; 1024];
let _ = stream.read(&mut buf).await.unwrap();
let consensus = testdata2::current_consensus_ns().2;
let resp = format!(
"HTTP/1.0 200 OK\r\nContent-Encoding: identity\r\nContent-Length: {}\r\n\r\n{consensus}",
consensus.len()
);
stream.write_all(resp.as_bytes()).await.unwrap();
});
engine
.fetch_consensus(&mut data, &[saddr], now)
.await
.unwrap();
match data {
ConsensusBoundData::Unverified { raw, ttl, .. } => {
assert_eq!(raw, testdata2::current_consensus_ns().2);
assert_eq!(ttl, now + UNVERIFIED_TTL);
}
_ => panic!("data is not unverified"),
}
}
#[tokio::test]
async fn state_auth_certs() {
let pool = testdata2::test_db();
let mut data = ConsensusBoundData::<Plain>::Unverified {
consensus: parse2::parse_netdoc(&ParseInput::new(
testdata2::current_consensus_ns().2,
"",
))
.unwrap(),
raw: testdata2::current_consensus_ns().2.to_owned(),
ttl: Timestamp::from(testdata2::valid_system_time()) + UNVERIFIED_TTL,
};
let mut engine = StaticEngine {
authorities: testdata2::current_auth_cert_contacts(),
tolerance: DirTolerance::default(),
rt: PreferredRuntime::current().unwrap(),
_phantom: Default::default(),
};
pool.get()
.unwrap()
.execute(
sql!(
"
DELETE FROM authority_key_certificate
WHERE :kp_auth_id_rsa_sha1 = ?1
"
),
params![db::Sha1::from(
testdata2::current_auth_cert_ids()[0].to_bytes()
)],
)
.unwrap();
assert_eq!(
db::read_tx(&pool, |tx| engine.determine_state(
tx,
&data,
testdata2::valid_system_time().into()
))
.unwrap()
.unwrap(),
State::AuthCerts
);
let server = TcpListener::bind("[::1]:0").await.unwrap();
let saddr = server.local_addr().unwrap();
tokio::spawn(async move {
let mut buf = [0; 1024];
let (mut stream, _) = server.accept().await.unwrap();
let _ = stream.read(&mut buf).await.unwrap();
let authcerts = testdata2::current_auth_certs()
.into_iter()
.map(|x| x.1)
.collect::<String>();
stream.write_all(format!(
"HTTP/1.0 200 OK\r\nContent-Encoding: identity\r\nContent-Length: {}\r\n\r\n{authcerts}",
authcerts.len()
).as_bytes()).await.unwrap();
});
engine
.auth_certs(
&pool,
&mut data,
&[saddr],
testdata2::valid_system_time().into(),
)
.await
.unwrap();
assert_eq!(
db::read_tx(&pool, |tx| engine.determine_state(
tx,
&data,
testdata2::valid_system_time().into(),
))
.unwrap()
.unwrap(),
State::StoreConsensus
);
let certs = db::read_tx(&pool, |tx| {
engine.certs_already(tx, testdata2::valid_system_time().into())
})
.unwrap()
.unwrap();
let got = certs
.into_iter()
.map(|c| c.dir_identity_key.to_rsa_identity())
.collect::<HashSet<_>>();
let expect = engine.authorities.v3idents().iter().copied().collect();
assert_eq!(got, expect);
engine.authorities = AuthorityContacts::builder().build().unwrap();
let state = db::read_tx(&pool, |tx| {
engine.determine_state(tx, &data, testdata2::valid_system_time().into())
})
.unwrap()
.unwrap();
assert_eq!(state, State::Hibernate);
}
#[tokio::test]
async fn certs_already() {
let pool = testdata2::test_db();
let engine = StaticEngine::<Plain> {
authorities: testdata2::current_auth_cert_contacts(),
tolerance: DirTolerance::default(),
rt: PreferredRuntime::current().unwrap(),
_phantom: Default::default(),
};
db::read_tx(&pool, |tx| {
let certs_already = engine
.certs_already(tx, testdata2::valid_system_time().into())
.unwrap();
assert_eq!(certs_already.len(), engine.authorities.v3idents().len());
assert!(certs_already.iter().all(|c| {
engine
.authorities
.v3idents()
.contains(&c.dir_identity_key.to_rsa_identity())
}));
let certs_already = engine
.certs_already(tx, testdata2::invalid_system_time().into())
.unwrap();
assert!(certs_already.is_empty());
})
.unwrap();
}
#[tokio::test]
async fn state_store_consensus() {
let pool = testdata2::test_db();
let unverified: Plain =
parse2::parse_netdoc(&ParseInput::new(testdata2::current_consensus_ns().2, ""))
.unwrap();
let engine = StaticEngine::<Plain> {
authorities: testdata2::current_auth_cert_contacts(),
tolerance: DirTolerance::default(),
rt: PreferredRuntime::current().unwrap(),
_phantom: Default::default(),
};
let now = Timestamp::from(testdata2::valid_system_time());
let mut data = ConsensusBoundData::<Plain>::Unverified {
consensus: unverified.clone(),
raw: testdata2::current_consensus_ns().2.to_string(),
ttl: now + UNVERIFIED_TTL,
};
pool.get()
.unwrap()
.execute_batch(sql!(
"
DELETE FROM consensus_router_descriptor_member;
DELETE FROM consensus_authority_voter;
DELETE FROM consensus;
"
))
.unwrap();
let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
.unwrap()
.unwrap();
assert_eq!(state, State::StoreConsensus);
engine.store_consensus(&pool, &mut data, now).unwrap();
assert!(matches!(&data, ConsensusBoundData::None));
let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
.unwrap()
.unwrap();
assert_eq!(state, State::LoadConsensus);
engine
.load_consensus(&pool, &mut data, now, &mut testing_rng())
.unwrap();
assert!(matches!(data, ConsensusBoundData::Verified { .. }));
}
}