use std::{
collections::{HashMap, HashSet, VecDeque},
fmt::Debug,
hash::Hash,
marker::PhantomData,
mem,
net::SocketAddr,
time::Duration,
};
use educe::Educe;
use r2d2::Pool;
use r2d2_sqlite::SqliteConnectionManager;
use rand::Rng;
use rusqlite::Transaction;
use tokio::net::TcpStream;
use tokio_util::compat::TokioAsyncReadCompatExt;
use tor_checkable::TimeBound;
use tor_dirclient::{
Error as DirClientError, RequestError, RequestFailedError,
request::{
AuthCertRequest, ConsensusRequest, MicrodescRequest, Requestable, RouterDescRequest,
},
};
use tor_dircommon::{authority::AuthorityContacts, config::DirTolerance};
use tor_error::internal;
use tor_netdoc::{
doc::{
authcert::{AuthCert, AuthCertKeyIds, AuthCertUnverified},
microdesc::Microdesc,
netstatus::{ConsensusFlavor, ConsensusVerifiabilityError},
routerdesc::RouterDescUnverified,
},
parse2::{
self, NetdocParseable, NetdocParseableUnverified, ParseError, ParseInput, VerifyFailed,
},
};
use tor_rtcompat::PreferredRuntime;
use tracing::{debug, warn};
use crate::{
database::{
self as db, AuthCertMeta, ConsensusMeta, ContentEncoding, DescriptorMeta, Sha1, Sha256,
Timestamp,
},
err::{AuthorityRequestError, DatabaseError, OperationError},
types::{
FlavoredConsensusUnverified, FlavoredDescriptor, FlavoredDescriptorMd,
FlavoredDescriptorPlain,
},
};
mod poc;
const UNVERIFIED_TTL: Duration = Duration::from_mins(10);
const DESCRIPTOR_LIMIT: Option<u64> = Some(92);
type DownloadAuthority = [SocketAddr];
#[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,
encodings: HashSet<ContentEncoding>,
_phantom: PhantomData<T>,
}
#[derive(Debug, Clone)]
enum ConsensusBoundData<T: FlavoredConsensusUnverified> {
None,
Unverified {
consensus: T,
raw: String,
ttl: Timestamp,
},
Verified {
consensus: ConsensusMeta<T>,
ttl: Timestamp,
futile: Box<FutileDescriptors>,
},
}
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,
futile,
} => {
let (missing_routers, missing_micros, missing_extras) = (
consensus.missing_routers(tx, futile.routers.refused(), Some(1))?,
consensus.missing_micros(tx, futile.micros.refused(), Some(1))?,
consensus.missing_extras(tx, futile.extras.refused(), Some(1))?,
);
if *ttl <= now {
State::FetchConsensus
} else if missing_routers.is_empty()
&& missing_micros.is_empty()
&& missing_extras.is_empty()
{
State::Hibernate
} else {
State::Descriptors
}
}
};
Ok(state)
}
async fn execute<R: Rng>(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &DownloadAuthority,
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 => self.descriptors(pool, data, endpoint, now).await,
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_else(|| internal!("database externally modified?"))?;
let ttl = consensus.ttl(rng);
let futile = Box::new(FutileDescriptors::default());
*data = ConsensusBoundData::Verified {
consensus,
ttl,
futile,
};
Ok(())
}
#[allow(clippy::string_slice)] async fn fetch_consensus(
&self,
data: &mut ConsensusBoundData<T>,
endpoint: &DownloadAuthority,
now: Timestamp,
) -> Result<(), AuthorityRequestError> {
let (raw, consensus) = self
.send_request(endpoint, ConsensusRequest::new(T::flavor()))
.await?;
let mut consensus = consensus.into_iter().collect::<VecDeque<_>>();
if consensus.len() != 1 {
return Err(AuthorityRequestError::Response(
"invalid number of consensus?",
));
}
let (consensus, start, end) = match consensus.pop_front().expect("pop failed?") {
(Ok(consensus), start, end) => (consensus, start, end),
(Err(_), _, _) => {
return Err(AuthorityRequestError::Response(
"invalid consensus received",
));
}
};
let raw = raw[start..end].to_string();
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: &DownloadAuthority,
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 unverified = match unverified {
Ok(v) => v,
Err(e) => {
debug!("ignoring invalid authority certificate: {e}");
return None;
}
};
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(AuthorityRequestError::NoRequestedDocumentsReturned)?;
}
db::rw_tx(pool, |tx| {
for (cert, data) in certs {
AuthCertMeta::insert(tx, self.encodings.iter().copied(), &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,
self.encodings.iter().copied(),
(&verified, &sigs),
&raw,
)?;
Ok::<_, OperationError>(())
})?
}
async fn descriptors(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &DownloadAuthority,
now: Timestamp,
) -> Result<(), OperationError> {
match T::flavor() {
ConsensusFlavor::Plain => {
self.descriptors_rd(pool, data, endpoint, now).await
}
ConsensusFlavor::Microdesc => self.descriptors_md(pool, data, endpoint, now).await,
}
}
async fn descriptors_rd(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &DownloadAuthority,
now: Timestamp,
) -> Result<(), OperationError> {
debug_assert_eq!(T::flavor(), ConsensusFlavor::Plain);
self.descriptors_agnostic::<RdDownloader>(pool, data, endpoint, now)
.await
}
async fn descriptors_md(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &DownloadAuthority,
now: Timestamp,
) -> Result<(), OperationError> {
debug_assert_eq!(T::flavor(), ConsensusFlavor::Microdesc);
self.descriptors_agnostic::<MdDownloader>(pool, data, endpoint, now)
.await
}
async fn descriptors_agnostic<D: DescriptorDownloader<T>>(
&self,
pool: &Pool<SqliteConnectionManager>,
data: &mut ConsensusBoundData<T>,
endpoint: &DownloadAuthority,
now: Timestamp,
) -> Result<(), OperationError> {
let (meta, futile) = match data {
ConsensusBoundData::Verified {
consensus, futile, ..
} => (consensus, futile),
_ => return Err(OperationError::Bug(internal!("data not verified"))),
};
let descriptors = db::read_tx(pool, |tx| D::query(tx, meta, futile, endpoint))??;
if descriptors.is_empty() {
debug!("not downloading any descriptors");
Err(OperationError::AuthorityRequest(
AuthorityRequestError::NoRequestedDocumentsReturned,
))?;
}
debug!("downloading the following descriptors: {descriptors:?}");
let requ = D::make_request(&descriptors);
let (raw, docs) = self.send_request::<_, D::Response>(endpoint, requ).await?;
let downloads = DescriptorDownloads::from_missing(descriptors.into_iter());
let downloads = D::process_downloads(self, downloads, docs, raw, now);
let progress = downloads
.values()
.find(|x| !matches!(x, DescriptorDownloadResult::NotFound))
.map(|_| ());
db::rw_tx(pool, |tx| D::insert(self, tx, futile, downloads, endpoint))??;
if progress.is_none() {
Err(OperationError::AuthorityRequest(
AuthorityRequestError::NoRequestedDocumentsReturned,
))?;
}
Ok(())
}
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: &DownloadAuthority,
requ: R,
) -> Result<(String, Vec<(Result<D, ParseError>, 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())
.map_err(tor_dirclient::Error::from)
});
drop(stream);
let resp = match resp.flatten() {
Ok(resp) => Ok(resp),
Err(DirClientError::RequestFailed(
ref outer @ RequestFailedError {
error: ref inner, ..
},
)) => match inner {
RequestError::EmptyRequest => {
warn!("we should not send an empty request");
return Ok(Default::default());
}
RequestError::EmptyResponse | RequestError::HttpStatus(404, _) => {
return Ok(Default::default());
}
_ => Err(outer.clone().into()),
},
Err(e) => Err(AuthorityRequestError::Bug(internal!(
"unhandled dirclient error: {e}"
))),
}?;
let parsed = parse2::parse_netdoc_multiple_sophisticated(&ParseInput::new(&resp, ""))?;
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)
}
}
trait DescriptorDownloader<T: FlavoredConsensusUnverified> {
type DocDigest: Debug + Hash + Eq + Clone + Copy;
type Descriptor: FlavoredDescriptor;
type Request: Requestable;
type Response: NetdocParseable;
fn query(
tx: &Transaction<'_>,
meta: &ConsensusMeta<T>,
futile: &FutileDescriptors,
endpoint: &DownloadAuthority,
) -> Result<HashSet<Self::DocDigest>, DatabaseError>;
fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request;
fn process_downloads(
engine: &StaticEngine<T>,
downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
raw: String,
now: Timestamp,
) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor>;
fn insert(
engine: &StaticEngine<T>,
tx: &Transaction<'_>,
futile: &mut FutileDescriptors,
downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
endpoint: &DownloadAuthority,
) -> Result<(), DatabaseError>;
}
fn downloader_common_insert<T: FlavoredConsensusUnverified, D: DescriptorDownloader<T>>(
engine: &StaticEngine<T>,
tx: &Transaction<'_>,
futile: &mut FutileDescriptors,
downloads: DescriptorDownloads<D::DocDigest, D::Descriptor>,
endpoint: &DownloadAuthority,
get_futile: fn(&mut FutileDescriptors) -> &mut FutileDescriptorSet<D::DocDigest>,
) -> Result<(), DatabaseError> {
for (digest, res) in downloads.into_iter() {
match res {
DescriptorDownloadResult::NotFound => {
get_futile(futile).set_not_found(digest, endpoint);
}
DescriptorDownloadResult::Refused => get_futile(futile).set_refused(digest),
DescriptorDownloadResult::Found(descriptor, raw) => {
DescriptorMeta::insert(tx, engine.encodings.iter().copied(), &descriptor, &raw)?;
}
}
}
Ok(())
}
struct RdDownloader;
impl<T: FlavoredConsensusUnverified> DescriptorDownloader<T> for RdDownloader {
type DocDigest = Sha1;
type Descriptor = FlavoredDescriptorPlain;
type Request = RouterDescRequest;
type Response = RouterDescUnverified;
fn query(
tx: &Transaction<'_>,
meta: &ConsensusMeta<T>,
futile: &FutileDescriptors,
endpoint: &DownloadAuthority,
) -> Result<HashSet<Self::DocDigest>, DatabaseError> {
meta.missing_routers(tx, futile.routers.excluded(endpoint), DESCRIPTOR_LIMIT)
}
fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request {
RouterDescRequest::from_iter(digests.iter().map(|sha1| sha1.0))
}
fn process_downloads(
engine: &StaticEngine<T>,
mut downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
raw: String,
now: Timestamp,
) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor> {
for (unverified, start, end) in docs {
let Ok(unverified) = unverified else {
continue;
};
let Some(raw) = raw.get(start..end) else {
warn!("parse2 returned invalid string slice: {start}..{end}");
continue;
};
let raw = raw.to_string();
let Some(sha1) = unverified.sigs.hashes.sha1 else {
warn!("accumulator contains no SHA-1?");
continue;
};
let sha1 = Sha1(sha1);
match downloads.get(&sha1) {
Some(DescriptorDownloadResult::NotFound) => {}
Some(DescriptorDownloadResult::Found(_, _) | DescriptorDownloadResult::Refused) => {
debug!("{sha1:?} contained multiple times in response");
continue;
}
None => {
debug!("ignoring unrequested router descriptor: {sha1:?}");
continue;
}
};
let sigs = unverified.sigs.clone();
let verified = match unverified.verify() {
Ok(verified) => verified,
Err(e) => {
debug!("ignoring invalid router descriptor: {sha1:?}: {e}");
continue;
}
};
let timely = match engine
.tolerance
.extend_tolerance(verified)
.if_valid_at(&now.into())
{
Ok(timely) => timely,
Err(e) => {
debug!("ignoring untimely router descriptor: {sha1:?}: {e}");
let prev = downloads.insert(sha1, DescriptorDownloadResult::Refused);
debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
continue;
}
};
let prev = downloads.insert(sha1, DescriptorDownloadResult::Found((timely, sigs), raw));
debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
}
downloads
}
fn insert(
engine: &StaticEngine<T>,
tx: &Transaction<'_>,
futile: &mut FutileDescriptors,
downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
endpoint: &DownloadAuthority,
) -> Result<(), DatabaseError> {
downloader_common_insert::<T, RdDownloader>(
engine,
tx,
futile,
downloads,
endpoint,
|futile| &mut futile.routers,
)
}
}
struct MdDownloader;
impl<T: FlavoredConsensusUnverified> DescriptorDownloader<T> for MdDownloader {
type DocDigest = Sha256;
type Descriptor = FlavoredDescriptorMd;
type Request = MicrodescRequest;
type Response = Microdesc;
fn query(
tx: &Transaction<'_>,
meta: &ConsensusMeta<T>,
futile: &FutileDescriptors,
endpoint: &DownloadAuthority,
) -> Result<HashSet<Self::DocDigest>, DatabaseError> {
meta.missing_micros(tx, futile.micros.excluded(endpoint), DESCRIPTOR_LIMIT)
}
fn make_request(digests: &HashSet<Self::DocDigest>) -> Self::Request {
MicrodescRequest::from_iter(digests.iter().map(|sha256| sha256.0))
}
fn process_downloads(
_engine: &StaticEngine<T>,
mut downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
docs: Vec<(Result<Self::Response, ParseError>, usize, usize)>,
raw: String,
_now: Timestamp,
) -> DescriptorDownloads<Self::DocDigest, Self::Descriptor> {
for (md, start, end) in docs {
let Some(raw) = raw.get(start..end) else {
warn!("parse2 returned invalid string slice: {start}..{end}");
continue;
};
let raw = raw.to_string();
let sha256 = Sha256::digest(raw.as_bytes());
match downloads.get(&sha256) {
Some(DescriptorDownloadResult::NotFound) => {}
Some(DescriptorDownloadResult::Found(_, _) | DescriptorDownloadResult::Refused) => {
debug!("{sha256:?} contained multiple times in response");
continue;
}
None => {
debug!("ignoring unrequested micro descriptor: {sha256:?}");
continue;
}
}
let Ok(md) = md else {
let prev = downloads.insert(sha256, DescriptorDownloadResult::Refused);
debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
continue;
};
let sha1 = Sha1::digest(raw.as_bytes());
let prev = downloads.insert(
sha256,
DescriptorDownloadResult::Found((md, sha1, sha256), raw),
);
debug_assert!(matches!(prev, Some(DescriptorDownloadResult::NotFound)));
}
downloads
}
fn insert(
engine: &StaticEngine<T>,
tx: &Transaction<'_>,
futile: &mut FutileDescriptors,
downloads: DescriptorDownloads<Self::DocDigest, Self::Descriptor>,
endpoint: &DownloadAuthority,
) -> Result<(), DatabaseError> {
downloader_common_insert::<T, MdDownloader>(
engine,
tx,
futile,
downloads,
endpoint,
|futile| &mut futile.micros,
)
}
}
#[derive(Debug, Clone, Default)]
struct FutileDescriptors {
routers: FutileDescriptorSet<Sha1>,
extras: FutileDescriptorSet<Sha1>,
micros: FutileDescriptorSet<Sha256>,
}
#[derive(Educe)]
#[educe(Debug, Clone, Default)]
struct FutileDescriptorSet<T: Debug + Clone + Copy + Eq + Hash> {
not_found: HashSet<(T, Box<DownloadAuthority>)>,
refused: HashSet<T>,
}
impl<T: Debug + Clone + Copy + Eq + Hash> FutileDescriptorSet<T> {
fn not_found(&self, endpoint: &DownloadAuthority) -> impl Iterator<Item = T> {
self.not_found
.iter()
.filter(|(_, this_endpoint)| **this_endpoint == *endpoint)
.map(|(d, _)| *d)
}
fn refused(&self) -> impl Iterator<Item = T> {
self.refused.iter().copied()
}
fn excluded(&self, endpoint: &DownloadAuthority) -> impl Iterator<Item = T> {
self.not_found(endpoint).chain(self.refused())
}
fn set_not_found(&mut self, digest: T, endpoint: &DownloadAuthority) {
self.not_found.insert((digest, endpoint.into()));
}
fn set_refused(&mut self, digest: T) {
self.refused.insert(digest);
}
}
#[derive(Debug, Clone)]
enum DescriptorDownloadResult<D: FlavoredDescriptor> {
Found(D, String),
NotFound,
Refused,
}
#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut, derive_more::IntoIterator)]
struct DescriptorDownloads<K, D: FlavoredDescriptor>(HashMap<K, DescriptorDownloadResult<D>>);
impl<K: Eq + Hash, D: FlavoredDescriptor> DescriptorDownloads<K, D> {
fn from_missing(digests: impl Iterator<Item = K>) -> Self {
Self(
digests
.map(|digest| (digest, DescriptorDownloadResult::NotFound))
.collect(),
)
}
}
#[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, iter};
use rusqlite::params;
use strum::IntoEnumIterator;
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;
fn static_engine<T>() -> StaticEngine<T> {
StaticEngine {
authorities: testdata2::current_auth_cert_contacts(),
tolerance: DirTolerance::default(),
rt: PreferredRuntime::current().unwrap(),
encodings: ContentEncoding::iter().collect(),
_phantom: Default::default(),
}
}
#[tokio::test]
async fn state_load_consensus() {
let pool = testdata2::test_db();
let mut data = ConsensusBoundData::<Plain>::None;
let engine = static_engine();
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 descriptor WHERE 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, iter::empty(), None).unwrap(),
HashSet::from([relay_to_remove])
);
assert!(
consensus
.missing_extras(tx, iter::empty(), None)
.unwrap()
.is_empty()
);
assert!(
consensus
.missing_micros(tx, iter::empty(), 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 = static_engine();
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 = static_engine();
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 = static_engine::<Plain>();
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 = static_engine();
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_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 { .. }));
}
async fn state_descriptors_agnostic<
T: FlavoredConsensusUnverified,
D: DescriptorDownloader<T>,
>(
descriptors: Vec<String>,
get_futile: fn(&FutileDescriptors) -> &FutileDescriptorSet<D::DocDigest>,
) {
let pool = testdata2::test_db();
let engine = static_engine::<T>();
let now = Timestamp::from(testdata2::valid_system_time());
let mut data = ConsensusBoundData::None;
let rng = &mut testing_rng();
let listener = TcpListener::bind("[::1]:0").await.unwrap();
let endpoint = listener.local_addr().unwrap();
tokio::spawn(async move {
let mut buf = [0; 1024];
let full = descriptors.iter().cloned().collect::<String>();
let single = descriptors.iter().take(1).cloned().collect::<String>();
let (mut stream, _) = listener.accept().await.unwrap();
let _ = stream.read(&mut buf).await.unwrap();
stream
.write_all(
format!(
"HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{}",
full.len(),
full
)
.as_bytes(),
)
.await
.unwrap();
drop(stream);
let (mut stream, _) = listener.accept().await.unwrap();
let _ = stream.read(&mut buf).await.unwrap();
stream
.write_all(
format!(
"HTTP/1.0 200 OK\r\nContent-Length: {}\r\n\r\n{}",
single.len(),
single
)
.as_bytes(),
)
.await
.unwrap();
});
db::rw_tx(&pool, |tx| tx.execute(sql!("DELETE FROM descriptor"), ()))
.unwrap()
.unwrap();
engine.load_consensus(&pool, &mut data, now, rng).unwrap();
let state = db::read_tx(&pool, |tx| engine.determine_state(tx, &data, now))
.unwrap()
.unwrap();
assert_eq!(state, State::Descriptors);
engine
.descriptors(&pool, &mut data, &[endpoint], now)
.await
.unwrap();
let (meta, futile) = match &data {
ConsensusBoundData::Verified {
consensus: meta,
futile,
..
} => (*meta, futile.clone()),
_ => panic!(),
};
let missing = db::read_tx(&pool, |tx| D::query(tx, &meta, &futile, &[endpoint]))
.unwrap()
.unwrap();
assert!(missing.is_empty());
assert!(get_futile(&futile).not_found.is_empty());
assert!(get_futile(&futile).refused.is_empty());
db::rw_tx(&pool, |tx| tx.execute(sql!("DELETE FROM descriptor"), ()))
.unwrap()
.unwrap();
let res = engine.descriptors(&pool, &mut data, &[endpoint], now).await;
assert!(matches!(
res,
Ok(())
| Err(OperationError::AuthorityRequest(
AuthorityRequestError::NoRequestedDocumentsReturned
))
));
let missing = db::read_tx(&pool, |tx| D::query(tx, &meta, &futile, &[endpoint]))
.unwrap()
.unwrap();
let futile = match &data {
ConsensusBoundData::Verified { futile, .. } => futile,
_ => panic!(),
};
assert!(!missing.is_empty());
assert_eq!(
missing,
get_futile(futile)
.not_found
.iter()
.filter_map(|(digest, this_endpoint)| if **this_endpoint == [endpoint] {
Some(*digest)
} else {
None
})
.collect::<HashSet<_>>()
);
assert!(get_futile(futile).refused.is_empty());
}
#[tokio::test]
async fn state_descriptors_plain() {
state_descriptors_agnostic::<Plain, RdDownloader>(
testdata2::current_router_descs()
.into_iter()
.map(|(_, _, raw)| raw)
.collect(),
|futile| &futile.routers,
)
.await;
}
#[tokio::test]
async fn state_descriptors_md() {
state_descriptors_agnostic::<Md, MdDownloader>(
testdata2::current_micro_descs()
.into_iter()
.map(|(_, raw)| raw)
.collect(),
|futile| &futile.micros,
)
.await;
}
}