Skip to main content

tor_netdoc/doc/
netstatus.rs

1//! Parsing implementation for networkstatus documents.
2//!
3//! In Tor, a networkstatus documents describes a complete view of the
4//! relays in the network: how many there are, how to contact them,
5//! and so forth.
6//!
7//! A networkstatus document can either be a "votes" -- an authority's
8//! view of the network, used as input to the voting process -- or a
9//! "consensus" -- a combined view of the network based on multiple
10//! authorities' votes, and signed by multiple authorities.
11//!
12//! A consensus document can itself come in two different flavors: a
13//! plain (unflavoured) consensus has references to router descriptors, and
14//! a "microdesc"-flavored consensus ("md") has references to
15//! microdescriptors.
16//!
17//! To keep an up-to-date view of the network, clients download
18//! microdescriptor-flavored consensuses periodically, and then
19//! download whatever microdescriptors the consensus lists that the
20//! client doesn't already have.
21//!
22//! For full information about the network status format, see
23//! [dir-spec.txt](https://spec.torproject.org/dir-spec).
24//!
25//! # Limitations
26//!
27//! NOTE: The consensus format has changes time, using a
28//! "consensus-method" mechanism.  This module is does not yet handle all
29//! all historical consensus-methods.
30//!
31//! NOTE: This module _does_ parse some fields that are not in current
32//! use, like relay nicknames, and the "published" times on
33//! microdescriptors. We should probably decide whether we actually
34//! want to do this.
35//!
36//! TODO: This module doesn't implement vote parsing at all yet.
37//!
38//! TODO: This module doesn't implement plain consensuses.
39//!
40//! TODO: We need an object safe trait that combines the common operations found
41//! on netstatus documents, so we can store one in a `Box<dyn CommonNs>` or
42//! something similar; otherwise interfacing applications have a hard time to
43//! process netstatus documents in a flavor agnostic fashion.
44//!
45//! TODO: More testing is needed!
46//!
47//! TODO: There should be accessor functions for most of the fields here.
48//! As with the other tor-netdoc types, I'm deferring those till I know what
49//! they should be.
50
51mod dir_source;
52mod rs;
53
54pub mod md;
55pub mod plain;
56pub mod vote;
57
58#[cfg(feature = "build_docs")]
59mod build;
60
61pub use proto_statuses_parse2_encode::ProtoStatusesNetdocParseAccumulator;
62
63use crate::doc::authcert::EncodedAuthCert;
64
65use crate::doc::authcert::{self, AuthCert, AuthCertKeyIds, AuthCertUnverified};
66use crate::encode::{
67    EncodeOrd, ItemArgument, ItemEncoder, ItemValueEncodable, NetdocEncodable, NetdocEncoder,
68};
69use crate::parse::keyword::Keyword;
70use crate::parse::parser::{Section, SectionRules, SectionRulesBuilder};
71use crate::parse::tokenize::{Item, ItemResult, NetDocReader};
72use crate::parse2::{
73    self, ArgumentError, ArgumentStream, ErrorProblem, IsStructural, ItemArgumentParseable,
74    ItemStream, ItemValueParseable, KeywordRef, NetdocParseable, NetdocParseableUnverified,
75    SignatureHashInputs, SignatureItemParseable, StopAt, UnparsedItem, VerifyFailed,
76};
77use crate::types::relay_flags::{self, DocRelayFlags};
78use crate::types::{self, *};
79use crate::util::PeekableIterator;
80use crate::{Error, KeywordEncodable, NetdocErrorKind as EK, NormalItemArgument, Pos};
81use std::collections::{BTreeSet, HashMap, HashSet};
82use std::fmt::{self, Display};
83use std::slice;
84use std::str::FromStr;
85use std::sync::Arc;
86use std::time::{self, SystemTime};
87use std::{net, result};
88use tor_basic_utils::iter_join;
89use tor_error::{Bug, HasKind, bad_api_usage, internal};
90use tor_protover::Protocols;
91use void::ResultVoidExt as _;
92
93use derive_deftly::{Deftly, define_derive_deftly};
94use digest::Digest;
95use educe::Educe;
96use itertools::Itertools;
97use saturating_time::SaturatingTime as _;
98use std::sync::LazyLock;
99use tor_checkable::{ExternallySigned, TimeBound, timed::TimeRangeBound};
100use tor_llcrypto as ll;
101use tor_llcrypto::pk::rsa::RsaIdentity;
102
103use serde::{Deserialize, Deserializer};
104
105#[cfg(feature = "build_docs")]
106pub use build::MdConsensusBuilder;
107#[cfg(feature = "build_docs")]
108pub use build::PlainConsensusBuilder;
109#[cfg(feature = "build_docs")]
110ns_export_each_flavor! {
111    ty: RouterStatusBuilder;
112}
113
114ns_export_each_variety! {
115    ty: Footer, RouterStatus, Preamble;
116}
117
118#[deprecated]
119pub use PlainConsensus as NsConsensus;
120#[deprecated]
121pub use PlainRouterStatus as NsRouterStatus;
122#[deprecated]
123pub use UncheckedPlainConsensus as UncheckedNsConsensus;
124#[deprecated]
125pub use UnvalidatedPlainConsensus as UnvalidatedNsConsensus;
126
127pub use rs::{RouterStatusMdDigestsVote, SoftwareVersion};
128
129pub use dir_source::{
130    ConsensusAuthoritySection, ConsensusAuthoritySectionConstructor, DirSource,
131    DirSourceConstructor, SupersededAuthorityKey,
132};
133
134define_constant_string! {
135    /// `network-status-version` version value
136    ///
137    /// This is the fixed string `3`.
138    ///
139    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:network-status-version>
140    //
141    // IMO this is nicer than the formulation with an enum.
142    // In practice we are not going to support other versions with the same parsing approach;
143    // probably not even with the same code.
144    NetworkStatusVersion = "3";
145}
146
147define_constant_string! {
148    /// The `status` value in a `vote-status` line in a consensus
149    ///
150    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-status>
151    VoteStatusConsensus = "consensus";
152}
153
154define_constant_string! {
155    /// The `vote` value in a `vote-status` line in a vote
156    ///
157    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-status>
158    VoteStatusVote = "vote";
159}
160
161/// `publiscation` field in routerstatus entry intro item other than in votes
162///
163/// Two arguments which are both ignored.
164/// This used to be an ISO8601 timestamp in anomalous two-argument format.
165///
166/// Nowadays, according to the spec, it can be a dummy value.
167/// So it can be a unit type.
168///
169/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:r>,
170/// except in votes which use [`Iso8601TimeSp`] instead.
171///
172/// **Not the same as** the `published` item:
173/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
174#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash, Ord, PartialOrd, Default)]
175#[allow(clippy::exhaustive_structs)]
176pub struct IgnoredPublicationTimeSp;
177
178/// The lifetime of a networkstatus document.
179///
180/// In a consensus, this type describes when the consensus may safely
181/// be used.  In a vote, this type describes the proposed lifetime for a
182/// consensus.
183///
184/// Aggregate of three netdoc preamble fields.
185#[derive(Clone, Debug, PartialEq, Eq, Deftly)]
186#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
187#[derive_deftly(Lifetime)]
188#[allow(clippy::exhaustive_structs)]
189pub struct Lifetime {
190    /// `valid-after` --- Time at which the document becomes valid
191    ///
192    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
193    ///
194    /// (You might see a consensus a little while before this time,
195    /// since voting tries to finish up before the.)
196    #[deftly(constructor)]
197    #[deftly(netdoc(single_arg))]
198    pub valid_after: Iso8601TimeSp,
199    /// `fresh-until` --- Time after which there is expected to be a better version
200    /// of this consensus
201    ///
202    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
203    ///
204    /// You can use the consensus after this time, but there is (or is
205    /// supposed to be) a better one by this point.
206    #[deftly(constructor)]
207    #[deftly(netdoc(single_arg))]
208    pub fresh_until: Iso8601TimeSp,
209    /// `valid-until` --- Time after which this consensus is expired.
210    ///
211    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:published>
212    ///
213    /// You should try to get a better consensus after this time,
214    /// though it's okay to keep using this one if no more recent one
215    /// can be found.
216    #[deftly(constructor)]
217    #[deftly(netdoc(single_arg))]
218    pub valid_until: Iso8601TimeSp,
219
220    #[doc(hidden)]
221    #[deftly(netdoc(skip))]
222    pub __non_exhaustive: (),
223}
224
225define_derive_deftly! {
226    /// Bespoke derive for `Lifetime`, for `new` and accessors
227    Lifetime:
228
229    ${defcond FIELD not(approx_equal($fname, __non_exhaustive))}
230
231    impl Lifetime {
232        /// Construct a new Lifetime.
233        pub fn new(
234            $( ${when FIELD} $fname: time::SystemTime, )
235        ) -> crate::Result<Self> {
236            // Make this now because otherwise literal `valid_after` here in the body
237            // has the wrong span - the compiler refuses to look at the argument.
238            // But we can refer to the field names.
239            let self_ = Lifetime {
240                $( ${when FIELD} $fname: $fname.into(), )
241                __non_exhaustive: (),
242            };
243            if self_.valid_after < self_.fresh_until && self_.fresh_until < self_.valid_until {
244                Ok(self_)
245            } else {
246                Err(EK::InvalidLifetime.err())
247            }
248        }
249      $(
250        ${when FIELD}
251
252        ${fattrs doc}
253        pub fn $fname(&self) -> time::SystemTime {
254            *self.$fname
255        }
256      )
257        /// Return true if this consensus is officially valid at the provided time.
258        pub fn valid_at(&self, when: time::SystemTime) -> bool {
259            *self.valid_after <= when && when <= *self.valid_until
260        }
261
262        /// Return the voting period implied by this lifetime.
263        ///
264        /// (The "voting period" is the amount of time in between when a consensus first
265        /// becomes valid, and when the next consensus is expected to become valid)
266        pub fn voting_period(&self) -> time::Duration {
267            let valid_after = self.valid_after();
268            let fresh_until = self.fresh_until();
269            fresh_until
270                .duration_since(valid_after)
271                .expect("Mis-formed lifetime")
272        }
273    }
274}
275use derive_deftly_template_Lifetime;
276
277/// A single consensus method
278///
279/// These are integers, but we don't do arithmetic on them.
280///
281/// As defined here:
282/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-methods>
283/// <https://spec.torproject.org/dir-spec/computing-consensus.html#flavor:microdesc>
284///
285/// As used in a `consensus-method` item:
286/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-method>
287#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Copy)] //
288#[derive(derive_more::From, derive_more::Into, derive_more::Display, derive_more::FromStr)]
289#[allow(clippy::exhaustive_structs)] // we're v unlikely to want to change this to u16 or u64
290pub struct ConsensusMethod(pub u32);
291impl NormalItemArgument for ConsensusMethod {}
292
293/// A set of consensus methods
294///
295/// Implements `ItemValueParseable` as required for `consensus-methods`,
296/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:consensus-methods>
297///
298/// There is also [`consensus_methods_comma_separated`] for `m` lines in votes.
299#[derive(Debug, Clone, Default, Eq, PartialEq, Ord, PartialOrd, Hash, Deftly)]
300#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
301#[non_exhaustive]
302pub struct ConsensusMethods {
303    /// Consensus methods.
304    pub methods: BTreeSet<ConsensusMethod>,
305}
306
307/// Module for use with parse2's `with`, to parse one argument of comma-separated consensus methods
308///
309/// As found in an `m` item in a vote:
310/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:m>
311pub mod consensus_methods_comma_separated {
312    use super::*;
313    use parse2::ArgumentError as AE;
314    use std::result::Result;
315
316    /// Parse
317    pub fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<ConsensusMethods, AE> {
318        let mut methods = BTreeSet::new();
319        for ent in args.next().ok_or(AE::Missing)?.split(',') {
320            let ent = ent.parse().map_err(|_| AE::Invalid)?;
321            if !methods.insert(ent) {
322                return Err(AE::Invalid);
323            }
324        }
325        Ok(ConsensusMethods { methods })
326    }
327
328    /// Encode
329    pub fn write_arg_onto(self_: &ConsensusMethods, out: &mut ItemEncoder) -> Result<(), Bug> {
330        out.args_raw_string(&iter_join(",", &self_.methods));
331        Ok(())
332    }
333}
334
335/// Contents of a `voting-delay` item in the network status preamble
336///
337/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:voting-delay>
338#[derive(Debug, Clone, Eq, PartialEq, Hash, Copy, Deftly)]
339#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
340#[allow(clippy::exhaustive_structs)]
341pub struct VotingDelay {
342    /// VoteSeconds
343    #[deftly(constructor)]
344    pub vote_seconds: u32,
345
346    /// DistSeconds
347    #[deftly(constructor)]
348    pub dist_seconds: u32,
349
350    #[doc(hidden)]
351    #[deftly(netdoc(skip))]
352    pub __non_exhaustive: (),
353}
354
355/// A set of named network parameters.
356///
357/// These are used to describe current settings for the Tor network,
358/// current weighting parameters for path selection, and so on.  They're
359/// encoded with a space-separated K=V format.
360///
361/// A `NetParams<i32>` is part of the validated directory manager configuration,
362/// where it is built (in the builder-pattern sense) from a transparent HashMap.
363///
364/// As found in `params` in a network status:
365/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:params>
366///
367/// The same syntax is also used, and this type used for parsing, in various other places,
368/// for example routerstatus entry `w` items (bandwidth weights):
369/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:w>
370//
371// TODO DIRAUTH torspec#401 Replace `String` with a suitable newtype
372// Currently:
373//  - Our parser allows any keyword that makes it into a netdoc argument,
374//    but it splits on the *first* `=` so a `NetParams<i32>` cannot parse a keyword with a `=`.
375//  - We provide constructors that allow any `String`, even ones containing space, `=`,
376//    newline, etc.
377//  - Encoding throws `Bug` if the resulting document will be clearly garbage,
378//    forbidding `=`, whitespace, and controls.  If the supplied keywords are bizarre,
379//    it may generate surprising documents (eg, containing exciting Unicode).
380#[derive(Debug, Clone, Educe, Eq, PartialEq)]
381#[educe(Default)]
382pub struct NetParams<T> {
383    /// Map from keys to values.
384    params: HashMap<String, T>,
385}
386
387impl<T> NetParams<T> {
388    /// Create a new empty list of NetParams.
389    #[allow(unused)]
390    pub fn new() -> Self {
391        NetParams {
392            params: HashMap::new(),
393        }
394    }
395    /// Retrieve a given network parameter, if it is present.
396    pub fn get<A: AsRef<str>>(&self, v: A) -> Option<&T> {
397        self.params.get(v.as_ref())
398    }
399    /// Return an iterator over all key value pairs in an arbitrary order.
400    pub fn iter(&self) -> impl Iterator<Item = (&String, &T)> {
401        self.params.iter()
402    }
403    /// Set or replace the value of a network parameter.
404    pub fn set(&mut self, k: String, v: T) {
405        self.params.insert(k, v);
406    }
407}
408
409impl<K: Into<String>, T> FromIterator<(K, T)> for NetParams<T> {
410    fn from_iter<I: IntoIterator<Item = (K, T)>>(i: I) -> Self {
411        NetParams {
412            params: i.into_iter().map(|(k, v)| (k.into(), v)).collect(),
413        }
414    }
415}
416
417impl<T> std::iter::Extend<(String, T)> for NetParams<T> {
418    fn extend<I: IntoIterator<Item = (String, T)>>(&mut self, iter: I) {
419        self.params.extend(iter);
420    }
421}
422
423impl<'de, T> Deserialize<'de> for NetParams<T>
424where
425    T: Deserialize<'de>,
426{
427    fn deserialize<D>(deserializer: D) -> std::result::Result<Self, D::Error>
428    where
429        D: Deserializer<'de>,
430    {
431        let params = HashMap::deserialize(deserializer)?;
432        Ok(NetParams { params })
433    }
434}
435
436/// A list of subprotocol versions that implementors should/must provide.
437///
438/// This struct represents a pair of (optional) items:
439/// `recommended-FOO-protocols` and `required-FOO-protocols`.
440///
441/// Each consensus has two of these: one for relays, and one for clients.
442///
443/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:required-relay-protocols>
444#[derive(Debug, Clone, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
445#[derive_deftly(Constructor)]
446#[allow(clippy::exhaustive_structs)]
447pub struct ProtoStatus {
448    /// Set of protocols that are recommended; if we're missing a protocol
449    /// in this list we should warn the user.
450    ///
451    /// `recommended-client-protocols` or `recommended-relay-protocols`
452    pub recommended: Protocols,
453
454    /// Set of protocols that are required; if we're missing a protocol
455    /// in this list we should refuse to start.
456    ///
457    /// `required-client-protocols` or `required-relay-protocols`
458    pub required: Protocols,
459
460    #[doc(hidden)]
461    #[serde(skip)]
462    pub __non_exhaustive: (),
463}
464
465impl ProtoStatus {
466    /// Check whether the list of supported protocols
467    /// is sufficient to satisfy this list of recommendations and requirements.
468    ///
469    /// If any required protocol is missing, returns [`ProtocolSupportError::MissingRequired`].
470    ///
471    /// Otherwise, if no required protocol is missing, but some recommended protocol is missing,
472    /// returns [`ProtocolSupportError::MissingRecommended`].
473    ///
474    /// Otherwise, if no recommended or required protocol is missing, returns `Ok(())`.
475    pub fn check_protocols(
476        &self,
477        supported_protocols: &Protocols,
478    ) -> Result<(), ProtocolSupportError> {
479        // Required protocols take precedence, so we check them first.
480        let missing_required = self.required.difference(supported_protocols);
481        if !missing_required.is_empty() {
482            return Err(ProtocolSupportError::MissingRequired(missing_required));
483        }
484        let missing_recommended = self.recommended.difference(supported_protocols);
485        if !missing_recommended.is_empty() {
486            return Err(ProtocolSupportError::MissingRecommended(
487                missing_recommended,
488            ));
489        }
490
491        Ok(())
492    }
493}
494
495/// A subprotocol that is recommended or required in the consensus was not present.
496#[derive(Clone, Debug, thiserror::Error)]
497#[cfg_attr(test, derive(PartialEq))]
498#[non_exhaustive]
499pub enum ProtocolSupportError {
500    /// At least one required protocol was not in our list of supported protocols.
501    #[error("Required protocols are not implemented: {0}")]
502    MissingRequired(Protocols),
503
504    /// At least one recommended protocol was not in our list of supported protocols.
505    ///
506    /// Also implies that no _required_ protocols were missing.
507    #[error("Recommended protocols are not implemented: {0}")]
508    MissingRecommended(Protocols),
509}
510
511impl ProtocolSupportError {
512    /// Return true if the suggested behavior for this error is a shutdown.
513    pub fn should_shutdown(&self) -> bool {
514        matches!(self, Self::MissingRequired(_))
515    }
516}
517
518impl HasKind for ProtocolSupportError {
519    fn kind(&self) -> tor_error::ErrorKind {
520        tor_error::ErrorKind::SoftwareDeprecated
521    }
522}
523
524/// A set of recommended and required protocols when running
525/// in various scenarios.
526///
527/// Represents the collection of four items: `{recommended,required}-{client,relay}-protocols`.
528///
529/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:required-relay-protocols>
530#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize, Deftly)]
531#[derive_deftly(Constructor)]
532#[allow(clippy::exhaustive_structs)]
533pub struct ProtoStatuses {
534    /// Lists of recommended and required subprotocol versions for clients
535    pub client: ProtoStatus,
536
537    /// Lists of recommended and required subprotocol versions for relays
538    pub relay: ProtoStatus,
539
540    #[doc(hidden)]
541    #[serde(skip)]
542    pub __non_exhaustive: (),
543}
544
545impl ProtoStatuses {
546    /// Return the list of recommended and required protocols for running as a client.
547    pub fn client(&self) -> &ProtoStatus {
548        &self.client
549    }
550
551    /// Return the list of recommended and required protocols for running as a relay.
552    pub fn relay(&self) -> &ProtoStatus {
553        &self.relay
554    }
555}
556
557/// List of recommended Tor versions
558///
559/// As seen in `client-versions` and `server-versions` in the preamble.
560///
561/// Technically these are supposed to be as according to
562/// "`version-spec.txt`" but we actually allow anything that doesn't contain commas.
563///
564/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:client-versions>
565/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:server-versions>
566///
567/// An empty set means no information, not no recommended versions.
568//
569// TODO should we have a CommaSeparated<T> type for arguments like this?
570// But maybe we wouldn't be able to use it here anyway because of
571// the special handling of the missing value.
572//
573// This is yet a third version number representation in arti!  Here it's just String.
574// TODO unify RecommendedTorVersions, RelayPlatform, TorVersion
575// When this is fixed, remove the workaround in netstatus::test::roundtrip_netstatus
576#[derive(Clone, Debug, Default, Eq, PartialEq, Ord, PartialOrd)] //
577#[derive(derive_more::Deref, derive_more::Into)]
578pub struct RecommendedTorVersions(BTreeSet<String>);
579
580/// Erroneous "recommended Tor versions" information
581#[derive(Clone, Debug, Eq, PartialEq, thiserror::Error)]
582#[non_exhaustive]
583pub enum InvalidRecommendedTorVersions {
584    /// Identical version appears twice
585    #[error("version {_0:?} contains whitespace")]
586    ContainsWhitespace(String),
587
588    /// Identical version appears twice
589    #[error("version {_0:?} is repeated")]
590    Repeated(String),
591}
592
593impl RecommendedTorVersions {
594    /// Return a `RecommendedTorVersions` that has no information
595    pub fn new_unknown() -> Self {
596        Self::default()
597    }
598
599    /// Does this `RecommendedTorVersions` have any information?
600    ///
601    /// Ie, is it not empty.
602    ///
603    /// The opposite of [`BTreeSet::is_empty()`] (which available via deref).
604    pub fn is_known(&self) -> bool {
605        !self.is_empty()
606    }
607
608    /// Construct a RecommendedTorVersions from a list of strings
609    #[allow(clippy::should_implement_trait)] // we can't due to coherence
610    pub fn from_iter<I, S>(i: I) -> Result<Self, InvalidRecommendedTorVersions>
611    where
612        I: IntoIterator<Item = S>,
613        S: AsRef<str>,
614    {
615        let mut set = BTreeSet::new();
616        for v in i {
617            let v = v.as_ref();
618            if v.is_empty() {
619                continue;
620            }
621            if v.chars().any(|c| c.is_whitespace()) {
622                return Err(InvalidRecommendedTorVersions::ContainsWhitespace(
623                    v.to_owned(),
624                ));
625            }
626            if !set.insert(v.to_owned()) {
627                return Err(InvalidRecommendedTorVersions::Repeated(v.to_owned()));
628            }
629        }
630        Ok(RecommendedTorVersions(set))
631    }
632}
633
634impl FromStr for RecommendedTorVersions {
635    type Err = InvalidRecommendedTorVersions;
636    fn from_str(s: &str) -> Result<Self, InvalidRecommendedTorVersions> {
637        Self::from_iter(s.split(','))
638    }
639}
640
641impl Display for RecommendedTorVersions {
642    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
643        write!(f, "{}", iter_join(",", &self.0))
644    }
645}
646
647impl NormalItemArgument for RecommendedTorVersions {}
648
649impl ItemValueEncodable for RecommendedTorVersions {
650    fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
651        out.args_raw_string(self);
652        Ok(())
653    }
654}
655
656impl ItemValueParseable for RecommendedTorVersions {
657    fn from_unparsed(mut item: UnparsedItem) -> Result<Self, ErrorProblem> {
658        const FIELD: &str = "versions";
659        item.check_no_object()?;
660        let args = item.args_mut();
661        let arg = args.next().unwrap_or("");
662        arg.parse::<Self>()
663            .map_err(|_| args.handle_error(FIELD, ArgumentError::Invalid))
664    }
665}
666
667/// A recognized 'flavor' of consensus document.
668///
669/// The enum is exhaustive because the addition/removal of a consensus flavor
670/// should indeed be a breaking change, as it would inevitable require
671/// interfacing code to think about the handling of it.
672///
673/// <https://spec.torproject.org/dir-spec/computing-consensus.html#flavors>
674#[derive(Copy, Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
675#[allow(clippy::exhaustive_enums)]
676pub enum ConsensusFlavor {
677    /// A "microdesc"-flavored consensus.  This is the one that
678    /// clients and relays use today.
679    Microdesc,
680    /// A "networkstatus"-flavored consensus.  It's used for
681    /// historical and network-health purposes.  Instead of listing
682    /// microdescriptor digests, it lists digests of full relay
683    /// descriptors.
684    Plain,
685}
686
687impl ConsensusFlavor {
688    /// Return the name of this consensus flavor.
689    pub fn name(&self) -> &'static str {
690        match self {
691            ConsensusFlavor::Plain => "ns", // spec bug, now baked in
692            ConsensusFlavor::Microdesc => "microdesc",
693        }
694    }
695    /// Try to find the flavor whose name is `name`.
696    ///
697    /// For historical reasons, an unnamed flavor indicates an "Plain"
698    /// document.
699    pub fn from_opt_name(name: Option<&str>) -> crate::Result<Self> {
700        match name {
701            Some("microdesc") => Ok(ConsensusFlavor::Microdesc),
702            Some("ns") | None => Ok(ConsensusFlavor::Plain),
703            Some(other) => {
704                Err(EK::BadDocumentType.with_msg(format!("unrecognized flavor {:?}", other)))
705            }
706        }
707    }
708}
709
710define_derive_deftly! {
711    /// Bespoke derives applied to [`DirectorySignatureHashAlgo`]
712    ///
713    /// Generates:
714    ///
715    ///  * [`DirectorySignaturesHashesAccu`]
716    ///  * [`DirectorySignaturesHashesAccu::update_from`]
717    ///  * [`DirectorySignaturesHashesAccu::hash_slice_for_verification`]
718    DirectorySignaturesHashesAccu:
719
720    ${define FNAME ${paste ${snake_case $vname}} }
721
722    /// `directory-signature`a hash algorithm argument
723    #[derive(Clone, Copy, Default, Debug, Eq, PartialEq, Deftly)]
724    #[derive_deftly(AsMutSelf)]
725    #[non_exhaustive]
726    pub struct DirectorySignaturesHashesAccu {
727      $(
728        ${vattrs doc}
729        pub $FNAME: Option<[u8; ${vmeta(hash_len) as expr}]>,
730      )
731    }
732
733    impl DirectorySignaturesHashesAccu {
734        /// Calculate the hash for a signature item and update this accumulator
735        fn update_from(
736            &mut self,
737            algo: &DigestAlgoInSignature,
738            body: &SignatureHashInputs,
739        ) {
740            // Update the hash in self.$UPDATE according to algorithm $AGLO
741            // (uses dynamic bindings of those parameters)
742            ${define HASH {
743                // Avoid recalculating if we don't need to
744                self.$UPDATE.get_or_insert_with(|| {
745                    let mut h = tor_llcrypto::d::$ALGO::new();
746                    h.update(body.body().body());
747                    h.update(body.signature_item_kw_spc);
748                    h.finalize().into()
749                });
750            }}
751
752            match &**algo {
753              $(
754                Some(KeywordOrString::Known($vtype)) => {
755                    ${define UPDATE $FNAME}
756                    ${define ALGO $vname}
757                    $HASH
758                }
759              )
760                None => {
761                    ${define UPDATE sha1}
762                    ${define ALGO Sha1}
763                    $HASH
764                }
765                Some(KeywordOrString::Unknown(..)) => {}
766            }
767        }
768
769        /// Return the hash value for a specific algorithm, as a slice
770        ///
771        /// `None` if the value wasn't computed.
772        /// That shouldn't happen.
773        fn hash_slice_for_verification(
774            &self,
775            algo: &DigestAlgoInSignature,
776        ) -> Option<&[u8]> {
777            match &**algo {
778              $(
779                Some(KeywordOrString::Known($vtype)) => Some(self.$FNAME.as_ref()?),
780              )
781                None => Some(self.sha1.as_ref()?),
782                Some(KeywordOrString::Unknown(..)) => None,
783            }
784        }
785    }
786}
787
788/// `directory-signature` hash algorithm argument
789#[derive(Clone, Copy, Debug, Eq, PartialEq, strum::Display, strum::EnumString, Deftly)]
790#[derive_deftly(DirectorySignaturesHashesAccu)]
791#[non_exhaustive]
792#[strum(serialize_all = "snake_case")]
793pub enum DirectorySignatureHashAlgo {
794    /// SHA-1
795    #[deftly(hash_len = "20")]
796    Sha1,
797    /// SHA-256
798    #[deftly(hash_len = "32")]
799    Sha256,
800}
801
802/// `algorithm` field in a `directory-signature` item
803///
804/// This is extremely bizarre: it's an *optional item at the start of the arguments*!
805// TODO SPEC #350
806///
807/// So we parse it with some kind of nightmarish lookahead.
808///
809/// Additionally, to be able to convey the signatures accurately, without breaking them,
810/// we must remember whether the argument was present.
811///
812/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:directory-signature>
813#[derive(Debug, Clone, derive_more::Deref, derive_more::DerefMut)]
814#[allow(clippy::exhaustive_structs)]
815pub struct DigestAlgoInSignature(pub Option<KeywordOrString<DirectorySignatureHashAlgo>>);
816
817impl ItemArgumentParseable for DigestAlgoInSignature {
818    fn from_args<'s>(args: &mut ArgumentStream<'s>) -> Result<Self, ArgumentError> {
819        let v = if args
820            .clone()
821            .next()
822            // Treat it as a fingerprint if it doesn't have any non-hex characters
823            // (including lowercase ones).  If we reuse this item for new algorithms
824            // they should have at least one letter g-z in their name.
825            .and_then(|s| s.chars().all(|c| c.is_ascii_hexdigit()).then_some(()))
826            .is_some()
827        {
828            // next argument looks enough like a fingerprint that we don't treat as an algo name
829            None
830        } else {
831            Some(KeywordOrString::from_args(args)?)
832        };
833        Ok(DigestAlgoInSignature(v))
834    }
835}
836impl ItemArgument for DigestAlgoInSignature {
837    fn write_arg_onto(&self, out: &mut ItemEncoder<'_>) -> Result<(), Bug> {
838        if let Some(y) = &self.0 {
839            y.write_arg_onto(out)?;
840        }
841        Ok(())
842    }
843}
844impl DigestAlgoInSignature {
845    /// Return the actual algorithm
846    ///
847    /// This handles the defaulting, where an absent argument means `sha1`.
848    pub fn algorithm(&self) -> &KeywordOrString<DirectorySignatureHashAlgo> {
849        self.as_ref()
850            .unwrap_or(&KeywordOrString::Known(DirectorySignatureHashAlgo::Sha1))
851    }
852}
853
854impl NormalItemArgument for DirectorySignatureHashAlgo {}
855
856/// The signature of a single directory authority on a networkstatus document.
857///
858/// Implements `ItemValueParseable` which parses without hashing anything;
859/// this is mostly useful for use by the `SignatureItemParseable` implementation.
860#[derive(Debug, Clone, Deftly)]
861#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
862#[non_exhaustive]
863pub struct Signature {
864    /// The name of the digest algorithm used to make the signature.
865    ///
866    /// Currently sha1 and sh256 are recognized.  Here we only support
867    /// sha256.
868    pub digest_algo: DigestAlgoInSignature,
869    /// Fingerprints of the keys for the authority that made
870    /// this signature.
871    #[deftly(netdoc(with = authcert::keyids_directory_signature_args))]
872    pub key_ids: AuthCertKeyIds,
873    /// The signature itself.
874    #[deftly(netdoc(object(label = "SIGNATURE"), with = types::raw_data_object))]
875    pub signature: Vec<u8>,
876}
877
878impl SignatureItemParseable for Signature {
879    type HashAccu = DirectorySignaturesHashesAccu;
880
881    fn from_unparsed_and_body(
882        item: UnparsedItem,
883        body: &SignatureHashInputs<'_>,
884        hash: &mut Self::HashAccu,
885    ) -> Result<Self, ErrorProblem> {
886        let signature = Signature::from_unparsed(item)?;
887        hash.update_from(&signature.digest_algo, body);
888        Ok(signature)
889    }
890}
891
892/// A collection of signatures that can be checked on a networkstatus document
893///
894/// This is derived from the signatures section of a netstatus,
895/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:signature>,
896/// but it is not isomorphic to it, and is not directly parseable.
897#[derive(Debug, Clone)]
898#[non_exhaustive]
899pub struct SignatureGroup {
900    /// The document hashes of the signed part of the document
901    ///
902    /// The pre-parse2 parser always sets `hashes.sha1` and `hashes.sha1_unnamed`
903    /// to the same value, which is wrong. which is
904    /// [bug #2530](https://gitlab.torproject.org/tpo/core/arti/-/work_items/2530)
905    pub hashes: DirectorySignaturesHashesAccu,
906    /// The signatures listed on the document.
907    pub signatures: Vec<Signature>,
908}
909
910/// Error which will prevent us from attempting to verify signatures on a consensus
911///
912/// This error occurs if we the consensus isn't signed by the right people,
913/// or we are lacking authcerts.
914///
915/// Does not represent actual verification errors.
916/// Those show up as `VerifyFailed`, typically [`ConsensusVerifyFailed::InvalidSignature`].
917///
918/// Can be converted to a `VerifyFailed`,
919/// giving [`InsufficientTrustedSigners`](VerifyFailed::InsufficientTrustedSigners).
920#[derive(Clone, Debug, thiserror::Error)]
921#[allow(clippy::exhaustive_enums)]
922pub enum ConsensusVerifiabilityError {
923    /// Insufficient trusted signers
924    #[error("consensus not signed by enough authorities")]
925    InsufficientTrustedSigners,
926
927    /// Insufficient trusted signers because we are missing authcerts
928    #[error("missing auth certs mean we could not verify enough consensuis signatures (need at least {deficit} more, out of {} that are missing)", missing.len())]
929    MissingAuthCerts {
930        /// The number of additional useful authcerts that would be sufficient
931        deficit: usize,
932        /// All the authcerts that would be useful
933        missing: HashSet<AuthCertKeyIds>,
934    },
935}
936
937/// Error encountered while verifying a consensus
938///
939/// Thrown by
940/// [`plain::NetworkStatusUnverified::verify`]
941/// and
942/// [`md::NetworkStatusUnverified::verify`].
943///
944/// Not used for problems with the validity period:
945/// that's handled by `tor-checkable` and shows up as [`tor_checkable::TimeValidityError`].
946///
947/// Can be converted to a `VerifyFailed` (which, in effect, summarises the error).
948#[derive(Clone, Debug, thiserror::Error)]
949#[non_exhaustive]
950pub enum ConsensusVerifyFailed {
951    /// Certificates or signatures insufficient
952    #[error("certs/sigs insufficient")]
953    CertificationInsufficient(#[from] ConsensusVerifiabilityError),
954
955    /// One or more signatures failed to verify
956    #[error("invalid signature")]
957    //
958    // Not `#[from]` because we don't want to accidentally convert
959    // ConsensusVerifiabilityError -> VerifyFailed -> ConsensusVerifyFailed
960    // since that would give the wrong variant.
961    InvalidSignature(#[source] VerifyFailed),
962}
963
964/// Error encountered while verifying a vote
965///
966/// Thrown by
967/// [`vote::NetworkStatusUnverified::verify`].
968///
969/// Not used for problems with the validity period:
970/// that's handled by `tor-checkable` and shows up as [`tor_checkable::TimeValidityError`].
971///
972/// Can be converted to a `VerifyFailed` (which, in effect, summarises the error).
973#[derive(Clone, Debug, thiserror::Error)]
974#[non_exhaustive]
975pub enum VoteVerifyFailed {
976    /// The document signature failed to verify
977    #[error("invalid signature")]
978    //
979    // Not `#[from]` because we don't want to accidentally convert
980    // VoteVerifyFailed::Something -> VerifyFailed -> VoteVerifyFailed
981    // since that would give the wrong variant.
982    InvalidSignature(#[source] VerifyFailed),
983
984    /// Authcert couldn't be parsed
985    #[error("unparseable authcert")]
986    AuthCertParseError(#[source] parse2::ParseError),
987
988    /// Authcert isn't valid for this vote's validity period
989    #[error("authcert not valid for vote period")]
990    AuthCertWrongValidity(#[source] tor_checkable::TimeValidityError),
991
992    /// Authcert is for a different authority
993    #[error("wrong authcert")]
994    AuthCertWrongAuthority,
995}
996
997/// A shared random value produced by the directory authorities.
998#[derive(
999    Debug, Clone, Copy, Eq, PartialEq, derive_more::From, derive_more::Into, derive_more::AsRef,
1000)]
1001// (This doesn't need to use CtByteArray; we don't really need to compare these.)
1002pub struct SharedRandVal([u8; 32]);
1003
1004/// A shared-random value produced by the directory authorities,
1005/// along with meta-information about that value.
1006#[derive(Debug, Clone, Deftly)]
1007#[non_exhaustive]
1008#[derive_deftly(ItemValueEncodable, ItemValueParseable)]
1009pub struct SharedRandStatus {
1010    /// How many authorities revealed shares that contributed to this value.
1011    pub n_reveals: u8,
1012    /// The current random value.
1013    ///
1014    /// The properties of the secure shared-random system guarantee
1015    /// that this value isn't predictable before it first becomes
1016    /// live, and that a hostile party could not have forced it to
1017    /// have any more than a small number of possible random values.
1018    pub value: SharedRandVal,
1019
1020    /// The time when this SharedRandVal becomes (or became) the latest.
1021    ///
1022    /// (This is added per proposal 342, assuming that gets accepted.)
1023    pub timestamp: Option<Iso8601TimeNoSp>,
1024}
1025
1026/// The two shared random values, `shared-rand-*-value`
1027///
1028/// As found in the consensus preamble
1029/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-current-value>
1030/// and a vote's authority section
1031/// <https://spec.torproject.org/dir-spec/consensus-formats.html#authority-item-shared-rand-value>
1032#[derive(Debug, Clone, Default, Deftly)]
1033#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1034#[allow(clippy::exhaustive_structs)]
1035pub struct SharedRandStatuses {
1036    /// Global shared-random value for the previous shared-random period.
1037    pub shared_rand_previous_value: Option<SharedRandStatus>,
1038
1039    /// Global shared-random value for the current shared-random period.
1040    pub shared_rand_current_value: Option<SharedRandStatus>,
1041
1042    #[doc(hidden)]
1043    #[deftly(netdoc(skip))]
1044    pub __non_exhaustive: (),
1045}
1046
1047/// Relay weight information - `w` item in routerstatus in consensuses
1048///
1049/// This is a combination of two representations of (subsets of) the same information,
1050/// from an optional `w` in the document.
1051///
1052///  * [`effective`](RelayWeightsItem::effective):
1053///
1054///    Always contains the effective weight, as [`RelayWeight`].
1055///    This is what is used by clients.
1056///    It does not record whether a `w` line was actually present.
1057///
1058///  * [`params`](RelayWeightsItem::params):
1059///
1060///    Can represent the presence and whole contents of the `w` line,
1061///    including all the known and unknown parameters.
1062///    This is within [`Unknown`], so it is only present with crate `feature = "retain-unknown"`,
1063///    and only some constructors/parsers record it.
1064///
1065/// # Parsing
1066///
1067/// Parsing is done with `NetdocParseableFields` rather than `ItemValueParseable`.
1068/// The `params` are [`Retained`](Unknown::Retained) if `retain_unknown_values` is
1069/// selected in [`parse2::ParseOptions`].
1070//
1071// We use NetdocParseableFields because the containing document, RouterStatus,
1072// contains `RelayWeightsItem` rather than `Option<RelayWeightsItem>`.
1073// The item parsing multiplicity machinery would see plain `RelayWeightsItem` as a required item.
1074//
1075// This representation also means so that if retaining unknown information is compiled out
1076// (ie, in clients) each routerstatus entry stored in memory does not need to record
1077// whether `w` was present, merely what the implications were.
1078//
1079// We can't use ItemValueParseable with #[deftly(netdoc(default))]
1080// because `RelayWeightsItem::default()` is a RelayWeightsItem that definitively
1081// contains no pazrameters, ie with `Unknown::Retained`,
1082// and is therefore only conditionally available.
1083/// # Encoding
1084///
1085/// Encoding requires knowing whether a `w` line is to be included, and its contents,
1086/// so is implemented only with if `effective` is `Unknown::Retained`.
1087/// The encoding impl is only compiled in with `"retain-unknown"`,
1088/// and throws [`Bug`] if applied to a `RelayWeightsItem` whose `params` are `Discarded`.
1089///
1090/// # Constructors
1091///
1092/// An "empty" `RelayWeightsItem` can be constructed with [`RelayWeightsItem::new_no_info`].
1093///
1094/// A `RelayWeightsItem` containing only the effective `RelayWeight`
1095/// can be constructed using [`RelayWeightsItem::from_effective`].
1096///
1097/// With `"retain-unknown"`:
1098/// a `RelayWeightsItem` can be constructed from a [`NetParams<u32>`] using `TryFrom`;
1099/// and, implements `Default`, which yields a `RelayWeightsItem`
1100/// representing the (known) absence of a `w` line.
1101//
1102// Fields are private to maintain the invariant.
1103#[derive(Debug, Clone)]
1104pub struct RelayWeightsItem {
1105    /// The effective relay weight
1106    effective: RelayWeight,
1107
1108    /// The complete parameter set, if available and `w` was present.
1109    params: Unknown<Option<NetParams<u32>>>,
1110}
1111
1112/// Relay weight information - `w` item in routerstatus in votes
1113#[derive(Debug, Clone, Deftly)]
1114#[derive_deftly(NetdocEncodableFields, NetdocParseableFields)]
1115#[allow(clippy::exhaustive_structs)] // this is always just this single item
1116pub struct VoteRelayWeightsItem {
1117    /// The parameters, uninterpreted.
1118    pub w: Option<NetParams<u32>>,
1119}
1120
1121/// Recognized weight fields on a single relay in a consensus
1122///
1123/// The part of a `w` item that we understand as a client.
1124#[non_exhaustive]
1125#[derive(Debug, Clone, Copy)]
1126pub enum RelayWeight {
1127    /// An unmeasured weight for a relay.
1128    Unmeasured(u32),
1129    /// An measured weight for a relay.
1130    Measured(u32),
1131}
1132
1133/// Error processing a `w` line's netparams into an effective relay weight
1134#[derive(Debug, Clone, thiserror::Error)]
1135#[non_exhaustive]
1136pub enum InvalidRelayWeights {
1137    /// Invalid value for `Unmeasured`
1138    #[error("invalid value for Unmeasured")]
1139    InvalidUnmeasured,
1140}
1141
1142/// Authority entry in a consensus - deprecated compatibility type alias
1143#[deprecated = "renamed to ConsensusAuthorityEntry"]
1144pub type ConsensusVoterInfo = ConsensusAuthorityEntry;
1145
1146/// Authority entry in a plain consensus - type alias provided for consistency
1147pub type PlainAuthorityEntry = ConsensusAuthorityEntry;
1148/// Authority entry in an md consensus - type alias provided for consistency
1149pub type MdAuthorityEntry = ConsensusAuthorityEntry;
1150
1151/// An authority entry as found in a consensus
1152///
1153/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority-entry>
1154///
1155/// See also [`VoteAuthorityEntry`]
1156//
1157// We don't use the `each_variety` system for this because:
1158//  1. That avoids separating the two consensus authority entry types, which are identical
1159//  2. The only common fields are `dir-source` and `contact`, so there is little duplication
1160#[derive(Debug, Clone, Deftly)]
1161#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1162#[allow(clippy::exhaustive_structs)]
1163pub struct ConsensusAuthorityEntry {
1164    /// Contents of the `dir-source` line about an authority
1165    #[deftly(constructor)]
1166    pub dir_source: DirSource,
1167
1168    /// Human-readable contact information about the authority
1169    //
1170    // If more non-intro fields get added that are the same in votes and cosensuses,
1171    // consider using each_variety.rs or breaking those fields out into
1172    // `AuthorityEntryCommon` implementing `NetdocParseableFields`, or something.
1173    #[deftly(constructor)]
1174    pub contact: ContactInfo,
1175
1176    /// Digest of the vote that the authority cast to contribute to
1177    /// this consensus.
1178    ///
1179    /// This is not a fixed-length, fixed-algorithm field.
1180    /// Bizarrely, the algorithm is supposed to be inferred from the length!
1181    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:vote-digest>
1182    #[deftly(netdoc(single_arg))]
1183    #[deftly(constructor)]
1184    pub vote_digest: B16U,
1185
1186    #[doc(hidden)]
1187    #[deftly(netdoc(skip))]
1188    pub __non_exhaustive: (),
1189}
1190
1191/// An authority entry as found in a vote
1192///
1193/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority-entry>
1194///
1195/// See also [`ConsensusAuthorityEntry`]
1196#[derive(Debug, Clone, Deftly)]
1197#[derive_deftly(Constructor, NetdocEncodable, NetdocParseable)]
1198#[allow(clippy::exhaustive_structs)]
1199pub struct VoteAuthorityEntry {
1200    /// Contents of the `dir-source` line about an authority
1201    #[deftly(constructor)]
1202    pub dir_source: DirSource,
1203
1204    /// Human-readable contact information about the authority
1205    #[deftly(constructor)]
1206    pub contact: ContactInfo,
1207
1208    /// `legacy-dir-key` - superseded authority identity key
1209    ///
1210    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:legacy-dir-key>
1211    #[deftly(netdoc(single_arg))]
1212    pub legacy_dir_key: Option<Fingerprint>,
1213
1214    /// `shared-rand-participate` - Indicate shared random participation
1215    ///
1216    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-participate>
1217    pub shared_rand_participate: Option<SharedRandParticipate>,
1218
1219    /// `shared-rand-commit` - Shared random commitment
1220    ///
1221    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
1222    pub shared_rand_commit: Vec<SharedRandCommit>,
1223
1224    /// Global shared-random values
1225    #[deftly(netdoc(flatten))]
1226    pub shared_rand: SharedRandStatuses,
1227
1228    #[doc(hidden)]
1229    #[deftly(netdoc(skip))]
1230    pub __non_exhaustive: (),
1231}
1232
1233/// `shared-rand-participate` in a vote authority entry
1234///
1235/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-participate>
1236//
1237// We could have done `shared_rand_participate: Option<()>` in VoteAuthorityEntry,
1238// but then we might end up with variables of type `&Option<()>` etc.
1239// whose meaning has been detached from its type.
1240//
1241// TODO DIRAUTH rework this according to the API design conclusion from !3977 when there is one
1242#[derive(Debug, Clone, Deftly)]
1243#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1244#[allow(clippy::exhaustive_structs)]
1245pub struct SharedRandParticipate {
1246    #[doc(hidden)]
1247    #[deftly(netdoc(skip))]
1248    pub __non_exhaustive: (),
1249}
1250
1251/// `shared-rand-commit` in a vote authority entry
1252///
1253/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
1254#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1255// If new protocols use this item with a different version, we'll call it an API break.
1256#[allow(clippy::exhaustive_enums)]
1257pub enum SharedRandCommit {
1258    /// Version 1, the only one supported
1259    V1(SharedRandCommitV1),
1260
1261    /// Other versions.  Cannot be encoded.
1262    // It's not clear that future versions will use this version mechanism.  torspec#408.
1263    Unknown {},
1264}
1265
1266/// `shared-rand-commit` in a vote authority entry
1267///
1268/// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:shared-rand-commit>
1269///
1270/// Version and hash are not explicitly represented.  See torspec#407.
1271///
1272/// `ItemValueEncodable` and `ItemValueParseable` impls do not include the fixed arguments;
1273/// in a netdoc, this type should be used within `SharedRandCommit::V1`.
1274#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Deftly)]
1275#[derive_deftly(Constructor, ItemValueEncodable, ItemValueParseable)]
1276#[allow(clippy::exhaustive_structs)]
1277pub struct SharedRandCommitV1 {
1278    /// Authority id key, recapitulated.
1279    // TODO this field shouldn't here at all torspec#407
1280    #[deftly(constructor)]
1281    h_kp_auth_id_rsa: Fingerprint,
1282
1283    /// Commitment
1284    ///
1285    /// `TIMESTAMP || SHA3_256(REVEAL)`, as per
1286    /// <https://spec.torproject.org/srv-spec/specification.html#COMMITREVEAL>
1287    //
1288    // TOOD we would like to replace this with a type that separates out the pieces!
1289    // But that would need a FixedB64 generic over some tor-bytes trait, or something.
1290    #[deftly(constructor)]
1291    commit: FixedB64<40>,
1292
1293    /// Reveal
1294    ///
1295    /// `TIMESTAMP || random number`, as per
1296    /// <https://spec.torproject.org/srv-spec/specification.html#COMMITREVEAL>
1297    reveal: Option<FixedB64<40>>,
1298
1299    #[doc(hidden)]
1300    #[deftly(netdoc(skip))]
1301    pub __non_exhaustive: (),
1302}
1303
1304impl SharedRandCommitV1 {
1305    /// The fixed arguments that precede the actual value in `shared-rand-commit 1 ...`
1306    const FIXED_ARGUMENTS: &[&str] = &["1", "sha3-256"];
1307}
1308impl ItemValueEncodable for SharedRandCommit {
1309    fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
1310        match self {
1311            SharedRandCommit::V1(values) => {
1312                for fixed in SharedRandCommitV1::FIXED_ARGUMENTS {
1313                    out.args_raw_string(fixed);
1314                }
1315                values.write_item_value_onto(out)
1316            }
1317            SharedRandCommit::Unknown {} => Err(internal!("encoding SharedRandCommit::Unknown")),
1318        }
1319    }
1320}
1321impl ItemValueParseable for SharedRandCommit {
1322    fn from_unparsed(mut item: UnparsedItem<'_>) -> Result<Self, ErrorProblem> {
1323        let mut fixed = SharedRandCommitV1::FIXED_ARGUMENTS.iter().copied();
1324        let args = item.args_mut();
1325        let version = args
1326            .next()
1327            .ok_or_else(|| args.handle_error("version", ArgumentError::Missing))?;
1328        if version != fixed.next().expect("nonempty") {
1329            return Ok(SharedRandCommit::Unknown {});
1330        }
1331        for exp in fixed {
1332            let got = args
1333                .next()
1334                .ok_or_else(|| args.handle_error(exp, ArgumentError::Missing))?;
1335            if got != exp {
1336                Err(args.handle_error(exp, ArgumentError::Invalid))?;
1337            }
1338        }
1339        let values = SharedRandCommitV1::from_unparsed(item)?;
1340        Ok(SharedRandCommit::V1(values))
1341    }
1342}
1343
1344// For `ConsensusAuthoritySection`, see `dir_source.rs`.
1345
1346define_derive_deftly! {
1347    /// Ad-hoc derive, `impl NetdocParseable for VoteAuthoritySection`
1348    ///
1349    /// We can't derive from `VoteAuthoritySection` with the normal macros, because
1350    /// it's not a document, with its own intro item.  It's just a collection of sub-documents.
1351    /// The netdoc derive macros don't have support for that - and it would be a fairly
1352    /// confusing thing to support because you'd end up with nested multiplicities and a whole
1353    /// variety of "intro item keywords" that were keywords for arbitrary sub-documents.
1354    ///
1355    /// Instead, we do that ad-hoc here.  It's less confusing because we don't need to
1356    /// worry about multiplicity, and because we know what only the outer document is
1357    /// that will contain this.
1358    VoteAuthoritySection:
1359
1360    ${defcond F_NORMAL not(fmeta(netdoc(skip)))}
1361
1362    impl NetdocParseable for VoteAuthoritySection {
1363        fn doctype_for_error() -> &'static str {
1364            "vote.authority.section"
1365        }
1366        fn is_intro_item_keyword(kw: KeywordRef<'_>) -> bool {
1367            VoteAuthorityEntry::is_intro_item_keyword(kw)
1368        }
1369        fn is_structural_keyword(kw: KeywordRef<'_>) -> Option<IsStructural> {
1370          $(
1371            ${when F_NORMAL}
1372            if let y @ Some(_) = $ftype::is_structural_keyword(kw) {
1373                return y;
1374            }
1375          )
1376            None
1377        }
1378        fn from_items<'s>(
1379            input: &mut ItemStream<'s>,
1380            stop_outer: stop_at!(),
1381        ) -> Result<Self, ErrorProblem> {
1382            let stop_inner = stop_outer
1383              $(
1384                ${when F_NORMAL}
1385                | StopAt($ftype::is_intro_item_keyword)
1386              )
1387            ;
1388            Ok(VoteAuthoritySection { $(
1389                ${when F_NORMAL}
1390                $fname: NetdocParseable::from_items(input, stop_inner)?,
1391            )
1392                __non_exhaustive: (),
1393            })
1394        }
1395    }
1396
1397    impl NetdocEncodable for VoteAuthoritySection {
1398        fn encode_unsigned(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
1399          $(
1400            ${when F_NORMAL}
1401            self.$fname.encode_unsigned(out)?;
1402          )
1403          Ok(())
1404        }
1405    }
1406}
1407
1408/// An authority section in a vote
1409///
1410/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:authority>
1411//
1412// We have split this out to help encapsulate vote/consensus-specific
1413// information in a forthcoming overall network status document type.
1414#[derive(Deftly, Clone, Debug)]
1415#[derive_deftly(VoteAuthoritySection, Constructor)]
1416#[allow(clippy::exhaustive_structs)]
1417pub struct VoteAuthoritySection {
1418    /// Authority entry
1419    #[deftly(constructor)]
1420    pub authority: VoteAuthorityEntry,
1421
1422    /// Authority key certificate
1423    #[deftly(constructor)]
1424    pub cert: EmbeddedCert<AuthCert, EncodedAuthCert>,
1425
1426    #[doc(hidden)]
1427    #[deftly(netdoc(skip))]
1428    pub __non_exhaustive: (),
1429}
1430
1431/// Fields in the footer of a consensus
1432///
1433/// <https://spec.torproject.org/dir-spec/consensus-formats.html#section:footer>
1434///
1435/// Not the whole footer, because it lacks the `directory-footer` item.
1436#[derive(Debug, Clone, Deftly)]
1437#[derive_deftly(Constructor, NetdocEncodableFields, NetdocParseableFields)]
1438#[allow(clippy::exhaustive_structs)]
1439pub struct ConsensusFooterFields {
1440    /// `bandwidth-weights`
1441    ///
1442    /// <https://spec.torproject.org/dir-spec/consensus-formats.html#item:bandwidth-weights>
1443    #[deftly(netdoc(default))]
1444    pub bandwidth_weights: NetParams<i32>,
1445
1446    #[doc(hidden)]
1447    #[deftly(netdoc(skip))]
1448    pub __non_exhaustive: (),
1449}
1450
1451/// A consensus document that lists relays along with their
1452/// microdescriptor documents.
1453pub type MdConsensus = md::Consensus;
1454
1455/// An MdConsensus that has been parsed and checked for timeliness,
1456/// but not for signatures.
1457pub type UnvalidatedMdConsensus = md::UnvalidatedConsensus;
1458
1459/// An MdConsensus that has been parsed but not checked for signatures
1460/// and timeliness.
1461pub type UncheckedMdConsensus = md::UncheckedConsensus;
1462
1463/// A consensus document that lists relays along with their
1464/// router descriptor documents.
1465pub type PlainConsensus = plain::Consensus;
1466
1467/// An PlainConsensus that has been parsed and checked for timeliness,
1468/// but not for signatures.
1469pub type UnvalidatedPlainConsensus = plain::UnvalidatedConsensus;
1470
1471/// An PlainConsensus that has been parsed but not checked for signatures
1472/// and timeliness.
1473pub type UncheckedPlainConsensus = plain::UncheckedConsensus;
1474
1475decl_keyword! {
1476    /// Keywords that can be used in votes and consensuses.
1477    // TODO: This is public because otherwise we can't use it in the
1478    // ParseRouterStatus crate.  But I'd rather find a way to make it
1479    // private.
1480    #[non_exhaustive]
1481    #[allow(missing_docs)]
1482    pub NetstatusKwd {
1483        // Header
1484        "network-status-version" => NETWORK_STATUS_VERSION,
1485        "vote-status" => VOTE_STATUS,
1486        "consensus-methods" => CONSENSUS_METHODS,
1487        "consensus-method" => CONSENSUS_METHOD,
1488        "published" => PUBLISHED,
1489        "valid-after" => VALID_AFTER,
1490        "fresh-until" => FRESH_UNTIL,
1491        "valid-until" => VALID_UNTIL,
1492        "voting-delay" => VOTING_DELAY,
1493        "client-versions" => CLIENT_VERSIONS,
1494        "server-versions" => SERVER_VERSIONS,
1495        "known-flags" => KNOWN_FLAGS,
1496        "flag-thresholds" => FLAG_THRESHOLDS,
1497        "recommended-client-protocols" => RECOMMENDED_CLIENT_PROTOCOLS,
1498        "required-client-protocols" => REQUIRED_CLIENT_PROTOCOLS,
1499        "recommended-relay-protocols" => RECOMMENDED_RELAY_PROTOCOLS,
1500        "required-relay-protocols" => REQUIRED_RELAY_PROTOCOLS,
1501        "params" => PARAMS,
1502        "bandwidth-file-headers" => BANDWIDTH_FILE_HEADERS,
1503        "bandwidth-file-digest" => BANDWIDTH_FILE_DIGEST,
1504        // "package" is now ignored.
1505
1506        // header in consensus, voter section in vote?
1507        "shared-rand-previous-value" => SHARED_RAND_PREVIOUS_VALUE,
1508        "shared-rand-current-value" => SHARED_RAND_CURRENT_VALUE,
1509
1510        // Voter section (both)
1511        "dir-source" => DIR_SOURCE,
1512        "contact" => CONTACT,
1513
1514        // voter section (vote, but not consensus)
1515        "legacy-dir-key" => LEGACY_DIR_KEY,
1516        "shared-rand-participate" => SHARED_RAND_PARTICIPATE,
1517        "shared-rand-commit" => SHARED_RAND_COMMIT,
1518
1519        // voter section (consensus, but not vote)
1520        "vote-digest" => VOTE_DIGEST,
1521
1522        // voter cert beginning (but only the beginning)
1523        "dir-key-certificate-version" => DIR_KEY_CERTIFICATE_VERSION,
1524
1525        // routerstatus
1526        "r" => RS_R,
1527        "a" => RS_A,
1528        "s" => RS_S,
1529        "v" => RS_V,
1530        "pr" => RS_PR,
1531        "w" => RS_W,
1532        "p" => RS_P,
1533        "m" => RS_M,
1534        "id" => RS_ID,
1535
1536        // footer
1537        "directory-footer" => DIRECTORY_FOOTER,
1538        "bandwidth-weights" => BANDWIDTH_WEIGHTS,
1539        "directory-signature" => DIRECTORY_SIGNATURE,
1540    }
1541}
1542
1543/// Shared parts of rules for all kinds of netstatus headers
1544static NS_HEADER_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> = LazyLock::new(|| {
1545    use NetstatusKwd::*;
1546    let mut rules = SectionRules::builder();
1547    rules.add(NETWORK_STATUS_VERSION.rule().required().args(1..=2));
1548    rules.add(VOTE_STATUS.rule().required().args(1..));
1549    rules.add(VALID_AFTER.rule().required());
1550    rules.add(FRESH_UNTIL.rule().required());
1551    rules.add(VALID_UNTIL.rule().required());
1552    rules.add(VOTING_DELAY.rule().args(2..));
1553    rules.add(CLIENT_VERSIONS.rule());
1554    rules.add(SERVER_VERSIONS.rule());
1555    rules.add(KNOWN_FLAGS.rule().required());
1556    rules.add(RECOMMENDED_CLIENT_PROTOCOLS.rule().args(1..));
1557    rules.add(RECOMMENDED_RELAY_PROTOCOLS.rule().args(1..));
1558    rules.add(REQUIRED_CLIENT_PROTOCOLS.rule().args(1..));
1559    rules.add(REQUIRED_RELAY_PROTOCOLS.rule().args(1..));
1560    rules.add(PARAMS.rule());
1561    rules
1562});
1563/// Rules for parsing the header of a consensus.
1564static NS_HEADER_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1565    use NetstatusKwd::*;
1566    let mut rules = NS_HEADER_RULES_COMMON_.clone();
1567    rules.add(CONSENSUS_METHOD.rule().args(1..=1));
1568    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1569    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1570    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1571    rules.build()
1572});
1573/*
1574/// Rules for parsing the header of a vote.
1575static NS_HEADER_RULES_VOTE: SectionRules<NetstatusKwd> = {
1576    use NetstatusKwd::*;
1577    let mut rules = NS_HEADER_RULES_COMMON_.clone();
1578    rules.add(CONSENSUS_METHODS.rule().args(1..));
1579    rules.add(FLAG_THRESHOLDS.rule());
1580    rules.add(BANDWIDTH_FILE_HEADERS.rule());
1581    rules.add(BANDWIDTH_FILE_DIGEST.rule().args(1..));
1582    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1583    rules
1584};
1585/// Rules for parsing a single voter's information in a vote.
1586static NS_VOTERINFO_RULES_VOTE: SectionRules<NetstatusKwd> = {
1587    use NetstatusKwd::*;
1588    let mut rules = SectionRules::new();
1589    rules.add(DIR_SOURCE.rule().required().args(6..));
1590    rules.add(CONTACT.rule().required());
1591    rules.add(LEGACY_DIR_KEY.rule().args(1..));
1592    rules.add(SHARED_RAND_PARTICIPATE.rule().no_args());
1593    rules.add(SHARED_RAND_COMMIT.rule().may_repeat().args(4..));
1594    rules.add(SHARED_RAND_PREVIOUS_VALUE.rule().args(2..));
1595    rules.add(SHARED_RAND_CURRENT_VALUE.rule().args(2..));
1596    // then comes an entire cert: When we implement vote parsing,
1597    // we should use the authcert code for handling that.
1598    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1599    rules
1600};
1601 */
1602/// Rules for parsing a single voter's information in a consensus
1603static NS_VOTERINFO_RULES_CONSENSUS: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1604    use NetstatusKwd::*;
1605    let mut rules = SectionRules::builder();
1606    rules.add(DIR_SOURCE.rule().required().args(6..));
1607    rules.add(CONTACT.rule().required());
1608    rules.add(VOTE_DIGEST.rule().required());
1609    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1610    rules.build()
1611});
1612/// Shared rules for parsing a single routerstatus
1613static NS_ROUTERSTATUS_RULES_COMMON_: LazyLock<SectionRulesBuilder<NetstatusKwd>> =
1614    LazyLock::new(|| {
1615        use NetstatusKwd::*;
1616        let mut rules = SectionRules::builder();
1617        rules.add(RS_A.rule().may_repeat().args(1..));
1618        rules.add(RS_S.rule().required());
1619        rules.add(RS_V.rule());
1620        rules.add(RS_PR.rule().required());
1621        rules.add(RS_W.rule());
1622        rules.add(RS_P.rule().args(2..));
1623        rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1624        rules
1625    });
1626
1627/// Rules for parsing a single routerstatus in an NS consensus
1628static NS_ROUTERSTATUS_RULES_PLAIN: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1629    use NetstatusKwd::*;
1630    let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1631    rules.add(RS_R.rule().required().args(8..));
1632    rules.build()
1633});
1634
1635/*
1636/// Rules for parsing a single routerstatus in a vote
1637static NS_ROUTERSTATUS_RULES_VOTE: SectionRules<NetstatusKwd> = {
1638    use NetstatusKwd::*;
1639        let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1640        rules.add(RS_R.rule().required().args(8..));
1641        rules.add(RS_M.rule().may_repeat().args(2..));
1642        rules.add(RS_ID.rule().may_repeat().args(2..)); // may-repeat?
1643        rules
1644    };
1645*/
1646/// Rules for parsing a single routerstatus in a microdesc consensus
1647static NS_ROUTERSTATUS_RULES_MDCON: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1648    use NetstatusKwd::*;
1649    let mut rules = NS_ROUTERSTATUS_RULES_COMMON_.clone();
1650    rules.add(RS_R.rule().required().args(6..));
1651    rules.add(RS_M.rule().required().args(1..));
1652    rules.build()
1653});
1654/// Rules for parsing consensus fields from a footer.
1655static NS_FOOTER_RULES: LazyLock<SectionRules<NetstatusKwd>> = LazyLock::new(|| {
1656    use NetstatusKwd::*;
1657    let mut rules = SectionRules::builder();
1658    rules.add(DIRECTORY_FOOTER.rule().required().no_args());
1659    // consensus only
1660    rules.add(BANDWIDTH_WEIGHTS.rule());
1661    rules.add(UNRECOGNIZED.rule().may_repeat().obj_optional());
1662    rules.build()
1663});
1664
1665impl ProtoStatus {
1666    /// Construct a ProtoStatus from two chosen keywords in a section.
1667    fn from_section(
1668        sec: &Section<'_, NetstatusKwd>,
1669        recommend_token: NetstatusKwd,
1670        required_token: NetstatusKwd,
1671    ) -> crate::Result<ProtoStatus> {
1672        /// Helper: extract a Protocols entry from an item's arguments.
1673        fn parse(t: Option<&Item<'_, NetstatusKwd>>) -> crate::Result<Protocols> {
1674            if let Some(item) = t {
1675                item.args_as_str()
1676                    .parse::<Protocols>()
1677                    .map_err(|e| EK::BadArgument.at_pos(item.pos()).with_source(e))
1678            } else {
1679                Ok(Protocols::new())
1680            }
1681        }
1682
1683        let recommended = parse(sec.get(recommend_token))?;
1684        let required = parse(sec.get(required_token))?;
1685        Ok(ProtoStatus {
1686            recommended,
1687            required,
1688            __non_exhaustive: (),
1689        })
1690    }
1691
1692    /// Return the protocols that are listed as "required" in this `ProtoStatus`.
1693    ///
1694    /// Implementations may assume that relays on the network implement all the
1695    /// protocols in the relays' required-protocols list.  Implementations should
1696    /// refuse to start if they do not implement all the protocols on their own
1697    /// (client or relay) required-protocols list.
1698    pub fn required_protocols(&self) -> &Protocols {
1699        &self.required
1700    }
1701
1702    /// Return the protocols that are listed as "recommended" in this `ProtoStatus`.
1703    ///
1704    /// Implementations should warn if they do not implement all the protocols
1705    /// on their own (client or relay) recommended-protocols list.
1706    pub fn recommended_protocols(&self) -> &Protocols {
1707        &self.recommended
1708    }
1709}
1710
1711impl<T> std::str::FromStr for NetParams<T>
1712where
1713    T: std::str::FromStr,
1714    T::Err: std::error::Error,
1715{
1716    type Err = Error;
1717    fn from_str(s: &str) -> crate::Result<Self> {
1718        /// Helper: parse a single K=V pair.
1719        fn parse_pair<U>(p: &str) -> crate::Result<(String, U)>
1720        where
1721            U: std::str::FromStr,
1722            U::Err: std::error::Error,
1723        {
1724            let parts: Vec<_> = p.splitn(2, '=').collect();
1725            if parts.len() != 2 {
1726                return Err(EK::BadArgument
1727                    .at_pos(Pos::at(p))
1728                    .with_msg("Missing = in key=value list"));
1729            }
1730            let num = parts[1].parse::<U>().map_err(|e| {
1731                EK::BadArgument
1732                    .at_pos(Pos::at(parts[1]))
1733                    .with_msg(e.to_string())
1734            })?;
1735            Ok((parts[0].to_string(), num))
1736        }
1737
1738        let params = s
1739            .split(' ')
1740            .filter(|p| !p.is_empty())
1741            .map(parse_pair)
1742            .try_collect()?;
1743        Ok(NetParams { params })
1744    }
1745}
1746
1747impl FromStr for SharedRandVal {
1748    type Err = Error;
1749    fn from_str(s: &str) -> crate::Result<Self> {
1750        let val: B64 = s.parse()?;
1751        let val = SharedRandVal(val.into_array()?);
1752        Ok(val)
1753    }
1754}
1755impl Display for SharedRandVal {
1756    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1757        Display::fmt(&B64::from(Vec::from(self.0)), f)
1758    }
1759}
1760impl NormalItemArgument for SharedRandVal {}
1761
1762impl SharedRandStatus {
1763    /// Parse a current or previous shared rand value from a given
1764    /// SharedRandPreviousValue or SharedRandCurrentValue.
1765    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
1766        match item.kwd() {
1767            NetstatusKwd::SHARED_RAND_PREVIOUS_VALUE | NetstatusKwd::SHARED_RAND_CURRENT_VALUE => {}
1768            _ => {
1769                return Err(Error::from(internal!(
1770                    "wrong keyword {:?} on shared-random value",
1771                    item.kwd()
1772                ))
1773                .at_pos(item.pos()));
1774            }
1775        }
1776        let n_reveals: u8 = item.parse_arg(0)?;
1777        let value: SharedRandVal = item.parse_arg(1)?;
1778        // Added in proposal 342
1779        let timestamp = item.parse_optional_arg::<Iso8601TimeNoSp>(2)?;
1780        Ok(SharedRandStatus {
1781            n_reveals,
1782            value,
1783            timestamp,
1784        })
1785    }
1786
1787    /// Return the actual shared random value.
1788    pub fn value(&self) -> &SharedRandVal {
1789        &self.value
1790    }
1791
1792    /// Return the timestamp (if any) associated with this `SharedRandValue`.
1793    pub fn timestamp(&self) -> Option<std::time::SystemTime> {
1794        self.timestamp.map(|t| t.0)
1795    }
1796}
1797
1798impl DirSource {
1799    /// Parse a "dir-source" item
1800    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Self> {
1801        if item.kwd() != NetstatusKwd::DIR_SOURCE {
1802            return Err(
1803                Error::from(internal!("Bad keyword {:?} on dir-source", item.kwd()))
1804                    .at_pos(item.pos()),
1805            );
1806        }
1807        let nickname = item
1808            .required_arg(0)?
1809            .parse()
1810            .map_err(|e: InvalidNickname| {
1811                EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
1812            })?;
1813        let identity = item.parse_arg(1)?;
1814        let hostname = item
1815            .required_arg(2)?
1816            .parse()
1817            .map_err(|e: InvalidInternetHost| {
1818                EK::BadArgument.at_pos(item.pos()).with_msg(e.to_string())
1819            })?;
1820        let ip = item.parse_arg(3)?;
1821        let dir_port = item.parse_arg(4)?;
1822        let or_port = item.parse_arg(5)?;
1823
1824        Ok(DirSource {
1825            nickname,
1826            identity,
1827            hostname,
1828            ip,
1829            dir_port,
1830            or_port,
1831            __non_exhaustive: (),
1832        })
1833    }
1834}
1835
1836impl ConsensusAuthorityEntry {
1837    /// Parse a single ConsensusAuthorityEntry from a voter info section.
1838    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusAuthorityEntry> {
1839        use NetstatusKwd::*;
1840        // this unwrap should be safe because if there is not at least one
1841        // token in the section, the section is unparsable.
1842        #[allow(clippy::unwrap_used)]
1843        let first = sec.first_item().unwrap();
1844        if first.kwd() != DIR_SOURCE {
1845            return Err(Error::from(internal!(
1846                "Wrong keyword {:?} at start of voter info",
1847                first.kwd()
1848            ))
1849            .at_pos(first.pos()));
1850        }
1851        let dir_source = DirSource::from_item(sec.required(DIR_SOURCE)?)?;
1852
1853        let contact = sec.required(CONTACT)?;
1854        // Ideally we would parse_args_as_str but that requires us to
1855        // impl From<InvalidContactInfo> for crate::Error which is wrong
1856        // because many it's a footgun which lets you just write ? here
1857        // resulting in lack of position information.
1858        // (This is a general problem with the error handling in crate::parse.)
1859        let contact = contact
1860            .args_as_str()
1861            .parse()
1862            .map_err(|err: InvalidContactInfo| {
1863                EK::BadArgument
1864                    .with_msg(err.to_string())
1865                    .at_pos(contact.pos())
1866            })?;
1867
1868        let vote_digest = sec.required(VOTE_DIGEST)?.parse_arg::<B16U>(0)?;
1869
1870        Ok(ConsensusAuthorityEntry {
1871            dir_source,
1872            contact,
1873            vote_digest,
1874            __non_exhaustive: (),
1875        })
1876    }
1877}
1878
1879impl RelayWeightsItem {
1880    /// Return a new `RelayWeightsItem` containing no information
1881    ///
1882    /// As if parsed from a document with no `w` line, discarding unknown information.
1883    pub fn new_no_info() -> Self {
1884        RelayWeightsItem {
1885            effective: RelayWeight::default(),
1886            params: Unknown::new_discard(),
1887        }
1888    }
1889
1890    /// Return a new `RelayWeightsItem` containing only the effective weight
1891    pub fn from_effective(effective: RelayWeight) -> Self {
1892        RelayWeightsItem {
1893            effective,
1894            params: Unknown::new_discard(),
1895        }
1896    }
1897
1898    /// Get the effective relay weight (bandwidth estimate) for path selection.
1899    ///
1900    /// Invariant: consistent with from [`params`](RelayWeightsItem::params),
1901    /// if `parsed` isn't [`Discarded`](Unknown::Discarded).
1902    //
1903    // We open-code this rather than deriving it so we can provide better docs.
1904    pub fn effective(&self) -> RelayWeight {
1905        self.effective
1906    }
1907
1908    /// Get the complete parameter set, if this information is available.
1909    ///
1910    /// After parsing, this is the parsed but not interpreted `w` item,
1911    /// or `None` if the document contained no `w` item.
1912    //
1913    // We open-code this rather than deriving it because we want to return
1914    // `Unknown<&...>` rather than `&Unknown<..>`, which the user would just have to .as_ref().
1915    pub fn params(&self) -> Unknown<&Option<NetParams<u32>>> {
1916        self.params.as_ref()
1917    }
1918
1919    /// Parse a routerweight from a "w" line.
1920    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<RelayWeightsItem> {
1921        if item.kwd() != NetstatusKwd::RS_W {
1922            return Err(
1923                Error::from(internal!("Wrong keyword {:?} on W line", item.kwd()))
1924                    .at_pos(item.pos()),
1925            );
1926        }
1927
1928        let params = item.args_as_str().parse()?;
1929        let effective = RelayWeight::from_net_params(&params).map_err(|e| e.at_pos(item.pos()))?;
1930
1931        Ok(RelayWeightsItem {
1932            effective,
1933            params: Unknown::new_discard(),
1934        })
1935    }
1936
1937    /// The keyword for parsing and encoding
1938    const KEYWORD: &str = "w";
1939}
1940
1941#[cfg(feature = "retain-unknown")]
1942impl Default for RelayWeightsItem {
1943    fn default() -> Self {
1944        RelayWeightsItem {
1945            effective: RelayWeight::default(),
1946            params: Unknown::Retained(None),
1947        }
1948    }
1949}
1950
1951impl RelayWeight {
1952    /// Return true if this weight is the result of a successful measurement
1953    pub fn is_measured(&self) -> bool {
1954        matches!(self, RelayWeight::Measured(_))
1955    }
1956
1957    /// Return true if this weight is nonzero
1958    pub fn is_nonzero(&self) -> bool {
1959        !matches!(self, RelayWeight::Unmeasured(0) | RelayWeight::Measured(0))
1960    }
1961
1962    /// Parse a routerweight from partially-parsed `w` line in the form of a `NetParams`
1963    ///
1964    /// This function is the common part shared between `parse2` and `parse`.
1965    fn from_net_params(params: &NetParams<u32>) -> crate::Result<RelayWeight> {
1966        params
1967            .try_into()
1968            .map_err(|e: InvalidRelayWeights| EK::BadArgument.with_msg(e.to_string()))
1969    }
1970}
1971
1972impl Default for RelayWeight {
1973    fn default() -> RelayWeight {
1974        RelayWeight::Unmeasured(0)
1975    }
1976}
1977
1978impl TryFrom<&NetParams<u32>> for RelayWeight {
1979    type Error = InvalidRelayWeights;
1980
1981    fn try_from(params: &NetParams<u32>) -> Result<RelayWeight, InvalidRelayWeights> {
1982        let bw = params.params.get("Bandwidth");
1983        let unmeas = params.params.get("Unmeasured");
1984
1985        let bw = match bw {
1986            None => return Ok(RelayWeight::Unmeasured(0)),
1987            Some(b) => *b,
1988        };
1989
1990        match unmeas {
1991            None | Some(0) => Ok(RelayWeight::Measured(bw)),
1992            Some(1) => Ok(RelayWeight::Unmeasured(bw)),
1993            _ => Err(InvalidRelayWeights::InvalidUnmeasured),
1994        }
1995    }
1996}
1997
1998#[cfg(feature = "retain-unknown")]
1999impl TryFrom<NetParams<u32>> for RelayWeightsItem {
2000    type Error = InvalidRelayWeights;
2001
2002    fn try_from(params: NetParams<u32>) -> Result<RelayWeightsItem, InvalidRelayWeights> {
2003        Ok(RelayWeightsItem {
2004            effective: (&params).try_into()?,
2005            params: Unknown::Retained(Some(params)),
2006        })
2007    }
2008}
2009
2010/// `parse2` impls for types in this modulea
2011///
2012/// Separate module for a separate namespace.
2013mod parse2_impls {
2014    use super::*;
2015    pub(super) use parse2::{
2016        ArgumentError as AE, ArgumentStream, ErrorProblem as EP, ItemArgumentParseable,
2017        ItemValueParseable, NetdocParseableFields,
2018    };
2019    use std::result::Result;
2020
2021    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
2022    impl<T: FromStr + NormalItemArgument> ItemValueParseable for NetParams<T>
2023    where
2024        T::Err: std::error::Error,
2025    {
2026        fn from_unparsed(item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2027            item.check_no_object()?;
2028            item.args_copy()
2029                .into_remaining()
2030                .parse()
2031                .map_err(item.invalid_argument_handler("parameters"))
2032        }
2033    }
2034
2035    impl NetdocParseableFields for RelayWeightsItem {
2036        type Accumulator = Option<NetParams<u32>>;
2037
2038        fn is_item_keyword(kw: KeywordRef) -> bool {
2039            kw == Self::KEYWORD
2040        }
2041
2042        fn accumulate_item(acc: &mut Self::Accumulator, item: UnparsedItem) -> Result<(), EP> {
2043            if acc.is_some() {
2044                return Err(EP::ItemRepeated);
2045            }
2046            item.check_no_object()?;
2047            let params = NetParams::from_unparsed(item)?;
2048            *acc = Some(params);
2049            Ok(())
2050        }
2051
2052        fn finish(params: Self::Accumulator, items: &ItemStream) -> Result<Self, EP> {
2053            let effective = params
2054                .as_ref()
2055                .map(TryFrom::try_from)
2056                .transpose()
2057                .map_err(|_| EP::OtherBadDocument("invalid information in `w` item"))?
2058                .unwrap_or_default();
2059
2060            let params = items.parse_options().retain_unknown_values.map(|()| params);
2061
2062            Ok(RelayWeightsItem { effective, params })
2063        }
2064    }
2065
2066    impl ItemValueParseable for rs::SoftwareVersion {
2067        fn from_unparsed(mut item: parse2::UnparsedItem<'_>) -> Result<Self, EP> {
2068            item.check_no_object()?;
2069            item.args_mut()
2070                .into_remaining()
2071                .parse()
2072                .map_err(item.invalid_argument_handler("version"))
2073        }
2074    }
2075
2076    impl ItemArgumentParseable for IgnoredPublicationTimeSp {
2077        fn from_args(a: &mut ArgumentStream) -> Result<IgnoredPublicationTimeSp, AE> {
2078            let mut next_arg = || a.next().ok_or(AE::Missing);
2079            let _: &str = next_arg()?;
2080            let _: &str = next_arg()?;
2081            Ok(IgnoredPublicationTimeSp)
2082        }
2083    }
2084}
2085
2086/// `encode` impls for types in this modulea
2087///
2088/// Separate module for a separate namespace.
2089mod encode_impls {
2090    use super::*;
2091    use std::result::Result;
2092    pub(crate) use {
2093        crate::encode::{ItemEncoder, ItemValueEncodable, NetdocEncodableFields},
2094        tor_error::Bug,
2095    };
2096
2097    impl NetdocEncodableFields for RelayWeightsItem {
2098        fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2099            if let Some(w) = self.params.as_ref().into_retained()? {
2100                w.write_item_value_onto(out.item(Self::KEYWORD))?;
2101            }
2102            Ok(())
2103        }
2104    }
2105
2106    // The NormalItemArgument bound ensures that this is applied only to sane types eg integers
2107    impl<T: NormalItemArgument + Ord + Display> ItemValueEncodable for NetParams<T> {
2108        fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2109            for (k, v) in self.iter().collect::<BTreeSet<_>>() {
2110                if k.is_empty()
2111                    || k.chars()
2112                        .any(|c| c.is_whitespace() || c.is_control() || c == '=')
2113                {
2114                    // TODO torspec#401 see TODO in NetParams<T> definition
2115                    return Err(bad_api_usage!(
2116                        "tried to encode NetParms with unreasonable keyword {k:?}"
2117                    ));
2118                }
2119                out.args_raw_string(&format_args!("{k}={v}"));
2120            }
2121            Ok(())
2122        }
2123    }
2124
2125    impl ItemValueEncodable for rs::SoftwareVersion {
2126        fn write_item_value_onto(&self, mut out: ItemEncoder) -> Result<(), Bug> {
2127            out.args_raw_string(self);
2128            Ok(())
2129        }
2130    }
2131
2132    impl ItemArgument for IgnoredPublicationTimeSp {
2133        fn write_arg_onto(&self, out: &mut ItemEncoder) -> Result<(), Bug> {
2134            out.args_raw_string(&"2000-01-01 00:00:01");
2135            Ok(())
2136        }
2137    }
2138}
2139
2140impl ConsensusFooterFields {
2141    /// Parse a directory footer from a footer section.
2142    fn from_section(sec: &Section<'_, NetstatusKwd>) -> crate::Result<ConsensusFooterFields> {
2143        use NetstatusKwd::*;
2144        sec.required(DIRECTORY_FOOTER)?;
2145
2146        let bandwidth_weights = sec
2147            .maybe(BANDWIDTH_WEIGHTS)
2148            .args_as_str()
2149            .unwrap_or("")
2150            .parse()?;
2151
2152        Ok(ConsensusFooterFields {
2153            bandwidth_weights,
2154            __non_exhaustive: (),
2155        })
2156    }
2157}
2158
2159/// `ProtoStatuses` parsing and encoding
2160///
2161/// Separate module for separate namespace
2162mod proto_statuses_parse2_encode {
2163    use super::encode_impls::*;
2164    use super::parse2_impls::*;
2165    use super::*;
2166    use paste::paste;
2167    use std::result::Result;
2168
2169    /// Implements `NetdocParseableFields` for `ProtoStatuses`
2170    ///
2171    /// We have this macro so that it's impossible to write things like
2172    /// ```text
2173    ///      ProtoStatuses {
2174    ///          client: ProtoStatus {
2175    ///              recommended: something something recommended_relay_versions something,
2176    /// ```
2177    ///
2178    /// (The structure of `ProtoStatuses` means the normal parse2 derive won't work for it.
2179    /// Note the bug above: the recommended *relay* version info is put in the *client* field.
2180    /// Preventing this bug must involve: avoiding writing twice the field name elements,
2181    /// such as `relay` and `client`, during this kind of construction/conversion.)
2182    macro_rules! impl_proto_statuses { { $( $rr:ident $cr:ident; )* } => { paste! {
2183        #[derive(Deftly)]
2184        #[derive_deftly(NetdocParseableFields)]
2185        // Only ProtoStatusesParseNetdocParseAccumulator is exposed.
2186        #[allow(unreachable_pub)]
2187        pub struct ProtoStatusesParseHelper {
2188            $(
2189                #[deftly(netdoc(default))]
2190                [<$rr _ $cr _protocols>]: Protocols,
2191            )*
2192        }
2193
2194        /// Partially parsed `ProtoStatuses`
2195        pub use ProtoStatusesParseHelperNetdocParseAccumulator
2196            as ProtoStatusesNetdocParseAccumulator;
2197
2198        impl NetdocParseableFields for ProtoStatuses {
2199            type Accumulator = ProtoStatusesNetdocParseAccumulator;
2200            fn is_item_keyword(kw: KeywordRef<'_>) -> bool {
2201                ProtoStatusesParseHelper::is_item_keyword(kw)
2202            }
2203            fn accumulate_item(
2204                acc: &mut Self::Accumulator,
2205                item: UnparsedItem<'_>,
2206            ) -> Result<(), EP> {
2207                ProtoStatusesParseHelper::accumulate_item(acc, item)
2208            }
2209            fn finish(acc: Self::Accumulator, items: &ItemStream<'_>) -> Result<Self, EP> {
2210                let parse = ProtoStatusesParseHelper::finish(acc, items)?;
2211                let mut out = ProtoStatuses::default();
2212                $(
2213                    out.$cr.$rr = parse.[< $rr _ $cr _protocols >];
2214                )*
2215                Ok(out)
2216            }
2217        }
2218
2219        impl NetdocEncodableFields for ProtoStatuses {
2220            fn encode_fields(&self, out: &mut NetdocEncoder) -> Result<(), Bug> {
2221              $(
2222                self.$cr.$rr.write_item_value_onto(
2223                    out.item(concat!(stringify!($rr), "-", stringify!($cr), "-protocols"))
2224                )?;
2225              )*
2226                Ok(())
2227            }
2228        }
2229    } } }
2230
2231    impl_proto_statuses! {
2232        recommended client;
2233        recommended relay;
2234        required client;
2235        required relay;
2236    }
2237}
2238
2239impl Signature {
2240    /// Parse a Signature from a directory-signature section
2241    fn from_item(item: &Item<'_, NetstatusKwd>) -> crate::Result<Signature> {
2242        if item.kwd() != NetstatusKwd::DIRECTORY_SIGNATURE {
2243            return Err(Error::from(internal!(
2244                "Wrong keyword {:?} for directory signature",
2245                item.kwd()
2246            ))
2247            .at_pos(item.pos()));
2248        }
2249
2250        let (digest_algo, id_fp, sk_fp) = if item.n_args() > 2 {
2251            (
2252                item.required_arg(0)?,
2253                item.required_arg(1)?,
2254                item.required_arg(2)?,
2255            )
2256        } else {
2257            // TODO #2530 digest_algo needs to depend on whether SHA1 was stated
2258            ("sha1", item.required_arg(0)?, item.required_arg(1)?)
2259        };
2260
2261        let digest_algo = digest_algo.to_string().parse().void_unwrap();
2262        let digest_algo = DigestAlgoInSignature(Some(digest_algo));
2263        let id_fingerprint = id_fp.parse::<Fingerprint>()?.into();
2264        let sk_fingerprint = sk_fp.parse::<Fingerprint>()?.into();
2265        let key_ids = AuthCertKeyIds {
2266            id_fingerprint,
2267            sk_fingerprint,
2268        };
2269        let signature = item.obj("SIGNATURE")?;
2270
2271        Ok(Signature {
2272            digest_algo,
2273            key_ids,
2274            signature,
2275        })
2276    }
2277
2278    /// Return true if this signature has the identity key and signing key
2279    /// that match a given cert.
2280    fn matches_cert(&self, cert: &AuthCert) -> bool {
2281        cert.key_ids() == self.key_ids
2282    }
2283
2284    /// If possible, find the right certificate for checking this signature
2285    /// from among a slice of certificates.
2286    fn find_cert<'a>(&self, certs: &'a [AuthCert]) -> Option<&'a AuthCert> {
2287        certs.iter().find(|&c| self.matches_cert(c))
2288    }
2289
2290    /// Find the certificate and assemble the pieces ready for verification
2291    ///
2292    /// `None` means precisely that we're missing the authcert.
2293    fn signature_to_verify<'r>(
2294        &'r self,
2295        signed_digest: &'r [u8],
2296        certs: &'r [AuthCert],
2297    ) -> Option<ConsensusSignatureToVerify> {
2298        let cert = self.find_cert(certs)?;
2299        let key = cert.signing_key();
2300        Some(ConsensusSignatureToVerify {
2301            key,
2302            signed_digest,
2303            signature: &self.signature,
2304        })
2305    }
2306}
2307
2308impl EncodeOrd for Signature {
2309    fn encode_cmp(&self, other: &Self) -> std::cmp::Ordering {
2310        let k: for<'s> fn(&'_ Signature) -> (&'_ _, &'_ _) = |s| (&s.key_ids, &s.signature);
2311        Ord::cmp(&k(self), &k(other))
2312    }
2313}
2314
2315/// Signature information in a consensus, to be verified
2316///
2317/// Used by callers of [`SignatureGroup::verify_general`],
2318/// to allow verification to be suppressed if all we wanted to know was
2319/// whether we have enough signatures and enough authcerts.
2320#[derive(Debug, Clone, Copy)]
2321struct ConsensusSignatureToVerify<'r> {
2322    /// KP_auth_sign_rsa
2323    key: &'r ll::pk::rsa::PublicKey,
2324
2325    /// The digest (actual RSA signature payload, before PKCS#11 padding)
2326    signed_digest: &'r [u8],
2327
2328    /// The RSA signature value
2329    signature: &'r [u8],
2330}
2331
2332/// Token indicating that signature verification has been done, if required
2333///
2334/// Prevents accidentally passing an unintended no-op function as
2335/// `do_verify` to [`SignatureGroup::verify_general`].
2336///
2337/// Write `SignatureVerifiedIfIntended {}` to construct this,
2338/// only in code which has actually done the verification,
2339/// or code which is deliberately not verifying at all.
2340pub(crate) struct SignatureVerifiedIfIntended {}
2341
2342impl<'r> ConsensusSignatureToVerify<'r> {
2343    /// Verify this signature
2344    ///
2345    fn verify(self) -> Result<SignatureVerifiedIfIntended, VerifyFailed> {
2346        self.key.verify(self.signed_digest, self.signature)?;
2347        Ok(SignatureVerifiedIfIntended {})
2348    }
2349}
2350
2351/// How `verify_general` should decide who is a trusted authority
2352///
2353/// Don't use this for other purposes
2354#[derive(Debug, Clone, Copy)]
2355pub(crate) enum VerifyGeneralTrustedAuthorities<'r> {
2356    /// Trust these authorities.
2357    TrustThese {
2358        /// The HKP_auth_id_rsa
2359        trusted: &'r [RsaIdentity],
2360    },
2361
2362    /// Document is a a vote, so OK if signed by any one of the listed authorities
2363    AnyOneOfThese {
2364        /// The HKP_auth_id_rsa
2365        trusted: &'r [RsaIdentity],
2366    },
2367
2368    /// For the benefit of `SignatureGroup::validate`, used by the old parser, only
2369    ///
2370    /// Every `AuthCert` passed to `verify_general` is a real authority (!)
2371    /// (But not necessarily a different one!)
2372    HazardouslyAssumeAllAuthCertsAreReal {
2373        /// Total number of authorities that we trust
2374        ///
2375        /// Used only to calculate the threshold
2376        n_authorities: usize,
2377    },
2378}
2379
2380/// Return the minimum number of authorities that we need signatures from
2381///
2382/// Enough is strictly more than half.
2383///
2384/// The returned value is a [`RangeFrom`](std::ops::RangeFrom), ie an inclusive range.
2385/// Its `start` value is the minimum acceptable number of authorities
2386/// from whom we have good signatures.
2387///
2388/// Should usually be followed by
2389/// [`.contains`](std::ops::RangeFrom::contains)`(&actual_number)`.
2390///
2391/// # Example
2392///
2393/// ```
2394/// use tor_netdoc::{doc::netstatus::consensus_threshold, parse2::VerifyFailed};
2395/// # fn main() -> Result<(), VerifyFailed> {
2396///
2397/// let n_trusted_authorities = 3;
2398/// let n_good_signatures_from_different_authorities = 2;
2399///
2400/// if consensus_threshold(n_trusted_authorities)
2401///      .contains(&n_good_signatures_from_different_authorities)
2402/// {
2403///     Ok(())
2404/// } else {
2405///     Err(VerifyFailed::InsufficientTrustedSigners)
2406/// }
2407/// # }
2408/// ```
2409pub fn consensus_threshold(n_authorities: usize) -> std::ops::RangeFrom<usize> {
2410    (n_authorities / 2) + 1 // strict majority
2411        ..
2412}
2413
2414impl SignatureGroup {
2415    // TODO: these functions are pretty similar and could probably stand to be
2416    // refactored a lot.
2417
2418    /// Helper: Return a pair of the number of possible authorities'
2419    /// signatures in this object for which we _could_ find certs, and
2420    /// a list of the signatures we couldn't find certificates for.
2421    fn list_missing(&self, certs: &[AuthCert]) -> (usize, Vec<&Signature>) {
2422        let mut ok: HashSet<RsaIdentity> = HashSet::new();
2423        let mut missing = Vec::new();
2424        for sig in &self.signatures {
2425            let id_fingerprint = &sig.key_ids.id_fingerprint;
2426            if ok.contains(id_fingerprint) {
2427                continue;
2428            }
2429            if sig.find_cert(certs).is_some() {
2430                ok.insert(*id_fingerprint);
2431                continue;
2432            }
2433
2434            missing.push(sig);
2435        }
2436        (ok.len(), missing)
2437    }
2438
2439    /// Given a list of authority identity key fingerprints, return true if
2440    /// this signature group is _potentially_ well-signed according to those
2441    /// authorities.
2442    fn could_validate(&self, authorities: &[&RsaIdentity]) -> bool {
2443        let mut signed_by: HashSet<RsaIdentity> = HashSet::new();
2444        for sig in &self.signatures {
2445            let id_fp = &sig.key_ids.id_fingerprint;
2446            if signed_by.contains(id_fp) {
2447                // Already found this in the list.
2448                continue;
2449            }
2450            if authorities.contains(&id_fp) {
2451                signed_by.insert(*id_fp);
2452            }
2453        }
2454
2455        consensus_threshold(authorities.len()).contains(&signed_by.len())
2456    }
2457
2458    /// Return true if the signature group defines a valid signature.
2459    ///
2460    /// A signature is valid if it signed by more than half of the
2461    /// authorities.  This API requires that `n_authorities` is the number of
2462    /// authorities we believe in, and that every cert in `certs` belongs
2463    /// to a real authority.
2464    fn validate(&self, n_authorities: usize, certs: &[AuthCert]) -> Result<(), VerifyFailed> {
2465        // TODO we ought to take the set of trusted authorities as an argument,
2466        // rather than use VGTA::HazardouslyAssumeAllAuthCertsAreReal.
2467        self.verify_general(
2468            VerifyGeneralTrustedAuthorities::HazardouslyAssumeAllAuthCertsAreReal { n_authorities },
2469            certs,
2470            |tv| tv.verify(),
2471        )
2472    }
2473
2474    /// Check signatures (maybe), but not timeliness
2475    ///
2476    /// Examines the signatures and collates them with authcerts.
2477    /// Performs the necessary consensus signature verifications, via `do_verify`.
2478    ///
2479    /// If there are not enough authcerts or not enough signatures,
2480    /// throws a `ConsensusVerifiabilityError`.
2481    ///
2482    /// Differs from [`SignatureGroup::validate`]:
2483    ///
2484    ///  * Intended also for use with types from parse2.
2485    ///
2486    ///  * Yields information about missing authcerts directly in the return value,
2487    ///    and can be used without actually doing the verification,
2488    ///    so there's no need for a separate "which certs are we missing" function.
2489    ///
2490    ///  * Threshold is passed as a parameter (wanted for votes).
2491    ///
2492    ///  * Ability to check authority identities, by passing `trusted_authorities`.
2493    ///    (done with `authorities_are_correct` in old parser,
2494    ///    apparently with no engineered safeguard against consensus user omitting to do so).
2495    ///
2496    ///    **If `trusted_authorities` is None, all authorities in `certs` are treated as trusted**.
2497    ///
2498    ///  * Returns `Result`, not a boolean
2499    ///
2500    ///  * We prefer the term `verify` to `validate`.  All this does is signature verification.
2501    ///
2502    fn verify_general<E>(
2503        &self,
2504        trusted_authorities: VerifyGeneralTrustedAuthorities,
2505        certs: &[AuthCert],
2506        do_verify: impl Fn(ConsensusSignatureToVerify) -> Result<SignatureVerifiedIfIntended, E>,
2507    ) -> Result<(), E>
2508    where
2509        ConsensusVerifiabilityError: Into<E>,
2510    {
2511        use VerifyGeneralTrustedAuthorities as TA;
2512
2513        // A set of the authorities (by identity) who have have signed
2514        // this document.  We use a set here in case `certs` has more
2515        // than one certificate for a single authority.
2516        let mut ok: HashSet<RsaIdentity> = HashSet::new();
2517        let mut missing = HashSet::new();
2518        let mut verify_failed = Ok(());
2519
2520        for sig in &self.signatures {
2521            // Exhaustive pattern makes it hard to accidentally ignore a field.
2522            let Signature {
2523                digest_algo,
2524                key_ids:
2525                    AuthCertKeyIds {
2526                        id_fingerprint,
2527                        // h_kp_auth_sign_rsa, which Signature::check_signature
2528                        // checks against the authcert.
2529                        sk_fingerprint: _,
2530                    },
2531                // Used by Signature::check_signature
2532                signature: _,
2533            } = sig;
2534
2535            match trusted_authorities {
2536                TA::TrustThese { trusted } | TA::AnyOneOfThese { trusted } => {
2537                    if !trusted.contains(id_fingerprint) {
2538                        continue;
2539                    }
2540                }
2541                TA::HazardouslyAssumeAllAuthCertsAreReal { .. } => {
2542                    // OK then!
2543                }
2544            }
2545
2546            if ok.contains(id_fingerprint) {
2547                // We already checked at least one signature using this
2548                // authority's identity fingerprint.
2549                continue;
2550            }
2551
2552            let Some(d) = self.hashes.hash_slice_for_verification(digest_algo) else {
2553                // We don't support this kind of digest for this kind
2554                // of document.
2555                continue;
2556            };
2557
2558            let Some(tv) = sig.signature_to_verify(d, certs) else {
2559                missing.insert(sig.key_ids);
2560                continue;
2561            };
2562            match do_verify(tv) {
2563                Ok::<SignatureVerifiedIfIntended, _>(_) => {
2564                    ok.insert(*id_fingerprint);
2565                }
2566                Err(e) => {
2567                    verify_failed = Err(e);
2568                }
2569            }
2570        }
2571
2572        let n_authorities = match trusted_authorities {
2573            TA::TrustThese { trusted } => trusted.len(),
2574            TA::HazardouslyAssumeAllAuthCertsAreReal { n_authorities: n } => n,
2575            TA::AnyOneOfThese { .. } => {
2576                // strict majority of 1 is 1, so n_authorites being 1 leads to threshold of 1
2577                // (doing it this way avoids having both thresholds and authority counts
2578                // in the same code area, which might lead to confusing one with the other.
2579                1
2580            }
2581        };
2582        let threshold = consensus_threshold(n_authorities);
2583
2584        if threshold.contains(&ok.len()) {
2585            Ok(())
2586        } else {
2587            // Throw the verification error if any of the verifications failed
2588            verify_failed?;
2589
2590            // Otherwise report that we're missing certs and/or signers
2591            Err(if missing.is_empty() {
2592                ConsensusVerifiabilityError::InsufficientTrustedSigners
2593            } else {
2594                let deficit = threshold.start - ok.len();
2595                ConsensusVerifiabilityError::MissingAuthCerts { missing, deficit }
2596            }
2597            .into())
2598        }
2599    }
2600}
2601
2602impl From<ConsensusVerifiabilityError> for VerifyFailed {
2603    fn from(cve: ConsensusVerifiabilityError) -> VerifyFailed {
2604        use ConsensusVerifiabilityError as CVE;
2605        use VerifyFailed as VF;
2606        match cve {
2607            CVE::InsufficientTrustedSigners => VF::InsufficientTrustedSigners,
2608            CVE::MissingAuthCerts { .. } => VF::InsufficientTrustedSigners,
2609        }
2610    }
2611}
2612
2613impl From<ConsensusVerifyFailed> for VerifyFailed {
2614    fn from(cvf: ConsensusVerifyFailed) -> VerifyFailed {
2615        use ConsensusVerifyFailed as CVF;
2616        use VerifyFailed as VF;
2617        match cvf {
2618            CVF::CertificationInsufficient { .. } => VF::InsufficientTrustedSigners,
2619            CVF::InvalidSignature { .. } => VF::VerifyFailed,
2620        }
2621    }
2622}
2623
2624#[cfg(test)]
2625mod test {
2626    // @@ begin test lint list maintained by maint/add_warning @@
2627    #![allow(clippy::bool_assert_comparison)]
2628    #![allow(clippy::clone_on_copy)]
2629    #![allow(clippy::dbg_macro)]
2630    #![allow(clippy::mixed_attributes_style)]
2631    #![allow(clippy::print_stderr)]
2632    #![allow(clippy::print_stdout)]
2633    #![allow(clippy::single_char_pattern)]
2634    #![allow(clippy::unwrap_used)]
2635    #![allow(clippy::unchecked_time_subtraction)]
2636    #![allow(clippy::useless_vec)]
2637    #![allow(clippy::needless_pass_by_value)]
2638    #![allow(clippy::string_slice)] // See arti#2571
2639    //! <!-- @@ end test lint list maintained by maint/add_warning @@ -->
2640    use super::*;
2641    use crate::doc::authcert::AuthCertUnverified;
2642    use crate::encode::{NetdocEncodable, NetdocEncodableFields};
2643    use crate::parse2::{ParseInput, parse_netdoc, parse_netdoc_multiple};
2644    use crate::test_support::regsub;
2645    use anyhow::Context as _;
2646    use assert_matches::assert_matches;
2647    use hex_literal::hex;
2648    use humantime::parse_rfc3339;
2649    use std::fmt::Debug;
2650    use std::fs;
2651    use std::time::Duration;
2652    use tor_checkable::TimeBound;
2653
2654    const CERTS: &str = include_str!("../../testdata/authcerts2.txt");
2655    const CONSENSUS: &str = include_str!("../../testdata/mdconsensus1.txt");
2656
2657    const PLAIN_CERTS: &str = include_str!("../../testdata2/cached-certs");
2658    const PLAIN_CONSENSUS: &str = include_str!("../../testdata2/cached-consensus");
2659
2660    fn read_bad(fname: &str) -> String {
2661        use std::fs;
2662        use std::path::PathBuf;
2663        let mut path = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
2664        path.push("testdata");
2665        path.push("bad-mdconsensus");
2666        path.push(fname);
2667
2668        fs::read_to_string(path).unwrap()
2669    }
2670
2671    #[test]
2672    fn parse_and_validate_md() -> crate::Result<()> {
2673        use std::net::SocketAddr;
2674        use tor_checkable::{SelfSigned, TimeBound};
2675        let mut certs = Vec::new();
2676        for cert in AuthCert::parse_multiple(CERTS)? {
2677            let cert = cert?.check_signature()?.dangerously_assume_timely();
2678            certs.push(cert);
2679        }
2680        let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2681
2682        assert_eq!(certs.len(), 3);
2683
2684        let (_, _, consensus) = MdConsensus::parse(CONSENSUS)?;
2685        let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2686
2687        // The set of authorities we know _could_ validate this cert.
2688        assert!(consensus.authorities_are_correct(&auth_ids));
2689        // A subset would also work.
2690        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2691        {
2692            // If we only believe in an authority that isn't listed,
2693            // that won't work.
2694            let bad_auth_id = (*b"xxxxxxxxxxxxxxxxxxxx").into();
2695            assert!(!consensus.authorities_are_correct(&[&bad_auth_id]));
2696        }
2697
2698        let missing = consensus.key_is_correct(&[]).err().unwrap();
2699        assert_eq!(3, missing.len());
2700        assert!(consensus.key_is_correct(&certs).is_ok());
2701        let missing = consensus.key_is_correct(&certs[0..1]).err().unwrap();
2702        assert_eq!(2, missing.len());
2703
2704        // here is a trick that had better not work.
2705        let same_three_times = vec![certs[0].clone(), certs[0].clone(), certs[0].clone()];
2706        let missing = consensus.key_is_correct(&same_three_times).err().unwrap();
2707
2708        assert_eq!(2, missing.len());
2709        assert!(consensus.is_well_signed(&same_three_times).is_err());
2710
2711        assert!(consensus.key_is_correct(&certs).is_ok());
2712        let consensus = consensus.check_signature(&certs)?;
2713
2714        assert_eq!(6, consensus.relays().len());
2715        let r0 = &consensus.relays()[0];
2716        assert_eq!(
2717            r0.md_digest(),
2718            &hex!("73dabe0a0468f4f7a67810a18d11e36731bb1d2ec3634db459100609f3b3f535")
2719        );
2720        assert_eq!(
2721            r0.rsa_identity().as_bytes(),
2722            &hex!("0a3057af2910415794d8ea430309d9ac5f5d524b")
2723        );
2724        assert!(!r0.weight().is_measured());
2725        assert!(!r0.weight().is_nonzero());
2726        let pv = &r0.protovers();
2727        assert!(pv.supports_subver("HSDir", 2));
2728        assert!(!pv.supports_subver("HSDir", 3));
2729        let ip4 = "127.0.0.1:5002".parse::<SocketAddr>().unwrap();
2730        let ip6 = "[::1]:5002".parse::<SocketAddr>().unwrap();
2731        assert!(r0.addrs().any(|a| a == ip4));
2732        assert!(r0.addrs().any(|a| a == ip6));
2733
2734        Ok(())
2735    }
2736
2737    #[test]
2738    fn parse_and_validate_ns() -> crate::Result<()> {
2739        use tor_checkable::{SelfSigned, TimeBound};
2740        let mut certs = Vec::new();
2741        for cert in AuthCert::parse_multiple(PLAIN_CERTS)? {
2742            let cert = cert?.check_signature()?.dangerously_assume_timely();
2743            certs.push(cert);
2744        }
2745        let auth_ids: Vec<_> = certs.iter().map(|c| c.id_fingerprint()).collect();
2746        assert_eq!(certs.len(), 4);
2747
2748        let (_, _, consensus) = PlainConsensus::parse(PLAIN_CONSENSUS)?;
2749        let consensus = consensus.dangerously_assume_timely().set_n_authorities(3);
2750        // The set of authorities we know _could_ validate this cert.
2751        assert!(consensus.authorities_are_correct(&auth_ids));
2752        // A subset would also work.
2753        assert!(consensus.authorities_are_correct(&auth_ids[0..1]));
2754
2755        assert!(consensus.key_is_correct(&certs).is_ok());
2756
2757        let _consensus = consensus.check_signature(&certs)?;
2758
2759        Ok(())
2760    }
2761
2762    #[test]
2763    fn test_bad() {
2764        use crate::Pos;
2765        fn check(fname: &str, e: &Error) {
2766            let content = read_bad(fname);
2767            let res = MdConsensus::parse(&content);
2768            assert!(res.is_err());
2769            assert_eq!(&res.err().unwrap(), e);
2770        }
2771
2772        check(
2773            "bad-flags",
2774            &EK::BadArgument
2775                .at_pos(Pos::from_line(27, 1))
2776                .with_msg("Flags out of order"),
2777        );
2778        check(
2779            "bad-md-digest",
2780            &EK::BadArgument
2781                .at_pos(Pos::from_line(40, 3))
2782                .with_msg("Invalid base64"),
2783        );
2784        check(
2785            "bad-weight",
2786            &EK::BadArgument
2787                .at_pos(Pos::from_line(67, 141))
2788                .with_msg("invalid digit found in string"),
2789        );
2790        check(
2791            "bad-weights",
2792            &EK::BadArgument
2793                .at_pos(Pos::from_line(51, 13))
2794                .with_msg("invalid digit found in string"),
2795        );
2796        check(
2797            "wrong-order",
2798            &EK::WrongSortOrder.at_pos(Pos::from_line(52, 1)),
2799        );
2800        check(
2801            "wrong-start",
2802            &EK::UnexpectedToken
2803                .with_msg("vote-status")
2804                .at_pos(Pos::from_line(1, 1)),
2805        );
2806        check("wrong-version", &EK::BadDocumentVersion.with_msg("10"));
2807    }
2808
2809    fn gettok(s: &str) -> crate::Result<Item<'_, NetstatusKwd>> {
2810        let mut reader = NetDocReader::new(s)?;
2811        let tok = reader.next().unwrap();
2812        assert!(reader.next().is_none());
2813        tok
2814    }
2815
2816    #[test]
2817    fn test_weight() {
2818        let w = gettok("w Unmeasured=1 Bandwidth=6\n").unwrap();
2819        let w = RelayWeightsItem::from_item(&w).unwrap();
2820        assert!(!w.effective.is_measured());
2821        assert!(w.effective.is_nonzero());
2822
2823        let w = gettok("w Bandwidth=10\n").unwrap();
2824        let w = RelayWeightsItem::from_item(&w).unwrap();
2825        assert!(w.effective.is_measured());
2826        assert!(w.effective.is_nonzero());
2827
2828        let w = RelayWeightsItem::new_no_info();
2829        assert!(!w.effective.is_measured());
2830        assert!(!w.effective.is_nonzero());
2831
2832        let w = gettok("w Mustelid=66 Cheato=7 Unmeasured=1\n").unwrap();
2833        let w = RelayWeightsItem::from_item(&w).unwrap();
2834        assert!(!w.effective.is_measured());
2835        assert!(!w.effective.is_nonzero());
2836
2837        let w = gettok("r foo\n").unwrap();
2838        let w = RelayWeightsItem::from_item(&w);
2839        assert!(w.is_err());
2840
2841        let w = gettok("r Bandwidth=6 Unmeasured=Frog\n").unwrap();
2842        let w = RelayWeightsItem::from_item(&w);
2843        assert!(w.is_err());
2844
2845        let w = gettok("r Bandwidth=6 Unmeasured=3\n").unwrap();
2846        let w = RelayWeightsItem::from_item(&w);
2847        assert!(w.is_err());
2848    }
2849
2850    #[test]
2851    fn test_netparam() {
2852        let p = "Hello=600 Goodbye=5 Fred=7"
2853            .parse::<NetParams<u32>>()
2854            .unwrap();
2855        assert_eq!(p.get("Hello"), Some(&600_u32));
2856
2857        let p = "Hello=Goodbye=5 Fred=7".parse::<NetParams<u32>>();
2858        assert!(p.is_err());
2859
2860        let p = "Hello=Goodbye Fred=7".parse::<NetParams<u32>>();
2861        assert!(p.is_err());
2862
2863        for bad_kw in ["What=The", "", "\n", "\0"] {
2864            let p = [(bad_kw, 42)].into_iter().collect::<NetParams<i32>>();
2865            let mut d = NetdocEncoder::new();
2866            let d = (|| {
2867                let i = d.item("bad-psrams");
2868                p.write_item_value_onto(i)?;
2869                d.finish()
2870            })();
2871            let _: tor_error::Bug = d.expect_err(bad_kw);
2872        }
2873    }
2874
2875    #[test]
2876    fn test_sharedrand() {
2877        let sr =
2878            gettok("shared-rand-previous-value 9 5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4\n")
2879                .unwrap();
2880        let sr = SharedRandStatus::from_item(&sr).unwrap();
2881
2882        assert_eq!(sr.n_reveals, 9);
2883        assert_eq!(
2884            sr.value.0,
2885            hex!("e4ba1d638c96c458532adc6957dc0080d03d37c7e5854087d0da90bf5ff4e72e")
2886        );
2887        assert!(sr.timestamp.is_none());
2888
2889        let sr2 = gettok(
2890            "shared-rand-current-value 9 \
2891                    5LodY4yWxFhTKtxpV9wAgNA9N8flhUCH0NqQv1/05y4 2022-01-20T12:34:56\n",
2892        )
2893        .unwrap();
2894        let sr2 = SharedRandStatus::from_item(&sr2).unwrap();
2895        assert_eq!(sr2.n_reveals, sr.n_reveals);
2896        assert_eq!(sr2.value.0, sr.value.0);
2897        assert_eq!(
2898            sr2.timestamp.unwrap().0,
2899            humantime::parse_rfc3339("2022-01-20T12:34:56Z").unwrap()
2900        );
2901
2902        let sr = gettok("foo bar\n").unwrap();
2903        let sr = SharedRandStatus::from_item(&sr);
2904        assert!(sr.is_err());
2905    }
2906
2907    #[test]
2908    fn test_protostatus() {
2909        let my_protocols: Protocols = "Link=7 Cons=1-5 Desc=3-10".parse().unwrap();
2910
2911        let outcome = ProtoStatus {
2912            recommended: "Link=7".parse().unwrap(),
2913            required: "Desc=5".parse().unwrap(),
2914            __non_exhaustive: (),
2915        }
2916        .check_protocols(&my_protocols);
2917        assert!(outcome.is_ok());
2918
2919        let outcome = ProtoStatus {
2920            recommended: "Microdesc=4 Link=7".parse().unwrap(),
2921            required: "Desc=5".parse().unwrap(),
2922            __non_exhaustive: (),
2923        }
2924        .check_protocols(&my_protocols);
2925        assert_eq!(
2926            outcome,
2927            Err(ProtocolSupportError::MissingRecommended(
2928                "Microdesc=4".parse().unwrap()
2929            ))
2930        );
2931
2932        let outcome = ProtoStatus {
2933            recommended: "Microdesc=4 Link=7".parse().unwrap(),
2934            required: "Desc=5 Cons=5-12 Wombat=15".parse().unwrap(),
2935            __non_exhaustive: (),
2936        }
2937        .check_protocols(&my_protocols);
2938        assert_eq!(
2939            outcome,
2940            Err(ProtocolSupportError::MissingRequired(
2941                "Cons=6-12 Wombat=15".parse().unwrap()
2942            ))
2943        );
2944    }
2945
2946    #[test]
2947    fn serialize_protostatus() {
2948        let ps = ProtoStatuses {
2949            client: ProtoStatus {
2950                recommended: "Link=1-5 LinkAuth=2-5".parse().unwrap(),
2951                required: "Link=5 LinkAuth=3".parse().unwrap(),
2952                __non_exhaustive: (),
2953            },
2954            relay: ProtoStatus {
2955                recommended: "Wombat=20-30 Knish=20-30".parse().unwrap(),
2956                required: "Wombat=20-22 Knish=25-27".parse().unwrap(),
2957                __non_exhaustive: (),
2958            },
2959            __non_exhaustive: (),
2960        };
2961        let json = serde_json::to_string(&ps).unwrap();
2962        let ps2 = serde_json::from_str(json.as_str()).unwrap();
2963        assert_eq!(ps, ps2);
2964
2965        let ps3: ProtoStatuses = serde_json::from_str(
2966            r#"{
2967            "client":{
2968                "required":"Link=5 LinkAuth=3",
2969                "recommended":"Link=1-5 LinkAuth=2-5"
2970            },
2971            "relay":{
2972                "required":"Wombat=20-22 Knish=25-27",
2973                "recommended":"Wombat=20-30 Knish=20-30"
2974            }
2975        }"#,
2976        )
2977        .unwrap();
2978        assert_eq!(ps, ps3);
2979    }
2980
2981    // consensuses are done in each_flavor.rs: see verify_error_netstatus
2982    #[test]
2983    fn verify_error_netstatus_vote() -> Result<(), anyhow::Error> {
2984        use VerifyFailed as VF;
2985        use VoteVerifyFailed as VVF;
2986        use vote::NetworkStatusUnverified as UV;
2987
2988        let file = "testdata2/v3-status-votes--1";
2989        let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
2990        let input = ParseInput::new(&text, file);
2991        let doc: UV = parse_netdoc(&input)?;
2992        let trusted = [doc.peek_alleged_authority()];
2993
2994        let edit_body = |f: &dyn Fn(&mut _)| {
2995            let (mut body, sigs) = doc.clone().unwrap_unverified();
2996            f(&mut body);
2997            UV::from_parts(body, sigs)
2998        };
2999
3000        // sabotage the overall signature
3001        {
3002            let mut doc = doc.clone();
3003            doc.sigs.sigs.directory_signature.signature.fill(0xff);
3004            assert_matches!(
3005                doc.verify(&trusted),
3006                Err(VVF::InvalidSignature(VF::VerifyFailed))
3007            );
3008        }
3009
3010        // wrong authority
3011        {
3012            let doc = doc.clone();
3013            assert_matches!(
3014                doc.verify(&[[0x55; _].into()]),
3015                Err(VVF::InvalidSignature(VF::InsufficientTrustedSigners))
3016            );
3017        }
3018
3019        // authcert is for a different authority
3020        {
3021            let doc = edit_body(&|body| {
3022                body.authority.authority.dir_source.identity.0 = [0x55; _].into();
3023            });
3024            assert_matches!(
3025                //
3026                doc.verify(&trusted),
3027                Err(VVF::AuthCertWrongAuthority)
3028            );
3029        }
3030
3031        // authcert is from a different time
3032        let with_mutated_lifetime = |f: &dyn Fn(&mut Lifetime)| {
3033            let doc = edit_body(&|body| f(&mut body.preamble.lifetime));
3034            assert_matches!(
3035                //
3036                doc.verify(&trusted),
3037                Err(VVF::AuthCertWrongValidity(_))
3038            );
3039        };
3040        let t_past = parse_rfc3339("1990-01-01T00:02:25Z")?;
3041        let t_future = parse_rfc3339("2010-01-01T00:02:25Z")?;
3042        with_mutated_lifetime(&|lifetime| lifetime.valid_after.0 = t_future);
3043        with_mutated_lifetime(&|lifetime| lifetime.fresh_until.0 = t_past);
3044        with_mutated_lifetime(&|lifetime| lifetime.valid_until.0 = t_past);
3045
3046        // syntactically invalid authcert
3047        {
3048            let mut text = text.clone();
3049            regsub(&mut text, "^dir-key-expires ", "dir-key-expires-SABOTAGED ");
3050            let input = ParseInput::new(&text, file);
3051            let doc: UV = parse_netdoc(&input)?;
3052            assert_matches!(
3053                //
3054                doc.verify(&trusted),
3055                Err(VVF::AuthCertParseError(..))
3056            );
3057        }
3058
3059        Ok(())
3060    }
3061
3062    #[cfg(feature = "retain-unknown")]
3063    #[allow(clippy::type_complexity)]
3064    pub(super) fn prep_netstatus_verify<UV: NetdocParseable>(
3065        file: &str,
3066    ) -> anyhow::Result<(UV, String, Vec<AuthCert>, Vec<RsaIdentity>, SystemTime)> {
3067        let text = fs::read_to_string(file).with_context(|| file.to_owned())?;
3068        let now = parse_rfc3339("2000-01-01T00:02:25Z")?;
3069
3070        let mut input = ParseInput::new(&text, file);
3071        input.retain_unknown_values();
3072
3073        let doc: UV = parse_netdoc(&input)?;
3074
3075        let certs = {
3076            let file = "testdata2/cached-certs";
3077            let text = fs::read_to_string(file)?;
3078            let input = ParseInput::new(&text, file);
3079            let certs: Vec<AuthCertUnverified> = parse_netdoc_multiple(&input)?;
3080            certs
3081                .into_iter()
3082                .map(|cert| cert.verify_selfcert(now))
3083                .collect::<Result<Vec<AuthCert>, _>>()?
3084        };
3085
3086        let authorities = certs.iter().map(|cert| *cert.fingerprint).collect_vec();
3087
3088        Ok((doc, text, certs, authorities, now))
3089    }
3090
3091    /// Check that a network document can be parsed and regenerated, mostly identically
3092    ///
3093    /// The regenerated encoded form doesn't need to be 100% identical:
3094    /// it is compared with a *munged* version of the the original input file,
3095    /// to cope with differences between C Tor and Arti.
3096    ///
3097    /// The mungings are:
3098    ///
3099    ///  * Some fields' syntax are adjusted, where C Tor and Arti disagree
3100    ///    in all kinds of network document.
3101    ///
3102    ///  * Document-specific, [`MungeForRoundtrip::adjust_exp`]
3103    #[cfg(feature = "retain-unknown")]
3104    fn roundtrip_netstatus<UV, V, VE>(
3105        // TODO DIRAUTH use include_str!, so, at call sites
3106        // https://gitlab.torproject.org/tpo/core/arti/-/merge_requests/4121#note_3428675
3107        file: &str,
3108        verify: impl FnOnce(UV, &[RsaIdentity], &[AuthCert]) -> Result<TimeRangeBound<V>, VE>,
3109        adjust_now: Duration,
3110    ) -> anyhow::Result<()>
3111    where
3112        UV: NetdocParseable + NetdocParseableUnverified + MungeForRoundtrip,
3113        UV::Signatures: Clone + Debug + NetdocEncodableFields,
3114        VE: Debug + std::error::Error + Send + Sync + 'static,
3115        V: Debug + NetdocEncodable,
3116    {
3117        let (doc, text, certs, authorities, now) = prep_netstatus_verify::<UV>(file)?;
3118
3119        let now = now + adjust_now;
3120
3121        let sigs = doc.inspect_unverified().1.sigs.clone();
3122
3123        let doc = verify(doc, &authorities, &certs)?.if_valid_at(&now)?;
3124
3125        println!("{doc:#?}");
3126
3127        let mut enc = NetdocEncoder::new();
3128        doc.encode_unsigned(&mut enc)?;
3129        sigs.encode_fields(&mut enc)?;
3130        let enc = enc.finish()?;
3131
3132        let mut exp: String = text.clone();
3133
3134        // TODO DIRAUTH torspec!507 C Tor emits padded base64 in shared-rand-* items.
3135        regsub(
3136            //
3137            &mut exp,
3138            r#"^(shared-rand-.*)$"#,
3139            |c: &regex::Captures| {
3140                let mut s = c[1].to_owned();
3141                regsub(&mut s, r#"="#, "");
3142                s
3143            },
3144        );
3145
3146        // We don't manage proper numerical sorting of version numbers.
3147        // Doing so is awkward.  See the (2nd) TODO on RecommendedTorVersions.
3148        regsub(
3149            //
3150            &mut exp,
3151            r#"^(client|server)-versions (.+)$"#,
3152            |c: &regex::Captures| -> String {
3153                format!(
3154                    "{}-versions {}",
3155                    &c[1],
3156                    iter_join(",", c[2].split(',').sorted()),
3157                )
3158            },
3159        );
3160
3161        let mut regsub = |re, repl| regsub(&mut exp, re, repl);
3162
3163        // C Tor writes empty versions lines with trailing space
3164        regsub(
3165            //
3166            r#"^((?:client|server)-versions) $"#,
3167            "$1",
3168        );
3169
3170        // C Tor emits `m` in varying places: after `a` in votes,
3171        // and at the end of each routerstatus in md consensuses.
3172        // We emit it at the start of each routerstatus, right after `r`.
3173        regsub(
3174            r#"(?x)
3175                   ( ^    r\ .* \n     )  #  ( r  )  $1, part before where we want to put m's
3176                   ( (?:     .* \n )*? )  #  (.*? )  $2, the rest, before the m's
3177                   ( (?:  m\ .* \n )+  )  #  ( m+ )  $3, one or more m's
3178            "#,
3179            r#"$1$3$2"#,
3180        );
3181
3182        UV::adjust_exp(&mut exp);
3183
3184        assert_eq_or_diff!(&exp, &enc);
3185
3186        Ok(())
3187    }
3188
3189    trait MungeForRoundtrip {
3190        /// Munge `s` so that it resembles the output of C Tor
3191        fn adjust_exp(exp: &mut String);
3192    }
3193
3194    /// Test that we can re-encode the consensus we parsed, and that we get the same thing back.
3195    ///
3196    /// Well, roughly the same thing.
3197    #[cfg(feature = "retain-unknown")]
3198    #[test]
3199    fn roundtrip_netstatus_plain() -> anyhow::Result<()> {
3200        roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3201            "testdata2/cached-consensus",
3202            plain::NetworkStatusUnverified::verify,
3203            Duration::ZERO,
3204        )
3205    }
3206
3207    impl MungeForRoundtrip for plain::NetworkStatusUnverified {
3208        fn adjust_exp(exp: &mut String) {
3209            let mut regsub = |re, repl| regsub(exp, re, repl);
3210
3211            // We emit the optional `ns`
3212            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:network-status-version
3213            regsub(
3214                r#"^network-status-version 3$"#,
3215                "network-status-version 3 ns",
3216            );
3217
3218            // C Tor writes nontrivial values for `publication` in rs `r` items,
3219            // but we use a fixed string.
3220            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:r
3221            regsub(
3222                r#"^(r \S+ \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3223                "$1 2000-01-01 00:00:01",
3224            );
3225        }
3226    }
3227
3228    #[cfg(feature = "retain-unknown")]
3229    #[test]
3230    fn roundtrip_netstatus_md() -> anyhow::Result<()> {
3231        roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3232            "testdata2/cached-microdesc-consensus",
3233            md::NetworkStatusUnverified::verify,
3234            Duration::ZERO,
3235        )
3236    }
3237
3238    impl MungeForRoundtrip for md::NetworkStatusUnverified {
3239        fn adjust_exp(exp: &mut String) {
3240            let mut regsub = |re, repl| regsub(exp, re, repl);
3241
3242            // C Tor writes nontrivial values for `publication` in rs `r` items,
3243            // but we use a fixed string.
3244            // https://spec.torproject.org/dir-spec/consensus-formats.html#item:r
3245            //
3246            // Not the same as in plain consensus: one fewer fields!
3247            regsub(
3248                r#"^(r \S+ \S+) \d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}"#,
3249                "$1 2000-01-01 00:00:01",
3250            );
3251        }
3252    }
3253
3254    #[cfg(feature = "retain-unknown")]
3255    #[test]
3256    fn roundtrip_netstatus_vote() -> anyhow::Result<()> {
3257        roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3258            "testdata2/v3-status-votes--1",
3259            |doc, trusted, _| vote::NetworkStatusUnverified::verify(doc, trusted),
3260            Duration::from_secs(20),
3261        )
3262    }
3263
3264    impl MungeForRoundtrip for vote::NetworkStatusUnverified {
3265        fn adjust_exp(exp: &mut String) {
3266            // C Tor writes items in consensuses a different order to in votes!
3267
3268            // C Tor writes different stats items with different floating point formats!
3269            let stats_massage_entry = |e: &str| {
3270                let mut e = e.to_owned();
3271                if e.contains('.') {
3272                    regsub(
3273                        &mut e,
3274                        // strip trailing 0's and then trailing `.`
3275                        r#"(?x)^ ( (?:wfu) = [0-9.]*? )( \.? 0+ ) $"#,
3276                        "$1",
3277                    );
3278                }
3279                e
3280            };
3281
3282            // C Tor writes stats items in votes in an apparently arbitrarily chosen order
3283            regsub(exp, r#"^stats (.+)$"#, |c: &regex::Captures| -> String {
3284                format!(
3285                    "stats {}",
3286                    iter_join(" ", c[1].split(' ').sorted().map(stats_massage_entry)),
3287                )
3288            });
3289
3290            let mut regsub = |re: &_, repl| regsub(exp, re, repl);
3291
3292            // C Tor writes *-protocols in an apparently arbitrarily chosen order
3293            regsub(
3294                r#"(?x)
3295                       ^ (recommended-relay-protocols\ .*)  \n
3296                         (recommended-client-protocols\ .*) \n
3297                         (required-relay-protocols\ .*)     \n
3298                         (required-client-protocols\ .*)    \n
3299                         (known-flags .*)$                  \n
3300                    "#,
3301                r#"$5
3302$2
3303$1
3304$4
3305$3
3306"#,
3307            );
3308
3309            // C Tor emits empty `client-versions` in consensuses, but not in votes.
3310            // (See also the fixup in `roundtrip_netstatus`, which relates to the *syntax*)
3311            //
3312            // Some of our inputs (eg the testdata2 votes) don't contain meaningful
3313            // info, so to make the C Tor output match our output, add them.
3314            regsub(
3315                r#"(?x) ^ (voting-delay\ .*) \n
3316                          (known-flags\ .*) \n"#,
3317                "$1
3318client-versions
3319server-versions
3320$2
3321",
3322            );
3323
3324            //#                         (?:  a\ .* \n )?    )   #    a? )           we want to put m's
3325
3326            for missing_field in [
3327                "bandwidth-file-headers", // TODO DIRAUTH implement
3328                "bandwidth-file-digest",  // TODO DIRAUTH implement
3329                "flag-thresholds",        // TODO DIRAUTH implement
3330            ] {
3331                regsub(&format!(r#"^{missing_field} .*\n"#), "");
3332            }
3333        }
3334    }
3335
3336    fn testdata_live(f: &str) -> String {
3337        // We implement an overrideable *prefix* rather than suffix, here,
3338        // so that we can access the files in a totally different directory.
3339        // (This is helpful with nailing-cargo, amongst other things.)
3340        let var = "TOR_NETDOC_TESTDATA_LIVE_PREFIX";
3341        let prefix = std::env::var_os(var)
3342            .map(|s| s.into_string().expect(var))
3343            .unwrap_or_else(|| "testdata-live/".into());
3344        format!("{prefix}{f}")
3345    }
3346
3347    #[allow(clippy::unnecessary_wraps)] // signature needs to match for roundtrip_netstatus
3348    fn unwrap_unverified_for_test<UV: NetdocParseableUnverified>(
3349        uv: UV,
3350        _ids: &[RsaIdentity],
3351        _certs: &[AuthCert],
3352    ) -> Result<TimeRangeBound<UV::Body>, std::convert::Infallible> {
3353        Ok(TimeRangeBound::new(uv.unwrap_unverified().0, ..))
3354    }
3355
3356    #[cfg(feature = "retain-unknown")]
3357    #[test]
3358    fn roundtrip_live_plain() -> anyhow::Result<()> {
3359        roundtrip_netstatus::<plain::NetworkStatusUnverified, _, _>(
3360            &testdata_live("consensus"),
3361            unwrap_unverified_for_test,
3362            Duration::ZERO,
3363        )
3364    }
3365
3366    #[cfg(feature = "retain-unknown")]
3367    #[test]
3368    fn roundtrip_live_md() -> anyhow::Result<()> {
3369        roundtrip_netstatus::<md::NetworkStatusUnverified, _, _>(
3370            &testdata_live("consensus-microdesc"),
3371            unwrap_unverified_for_test,
3372            Duration::ZERO,
3373        )
3374    }
3375
3376    #[cfg(feature = "retain-unknown")]
3377    #[test]
3378    fn roundtrip_live_vote() -> anyhow::Result<()> {
3379        roundtrip_netstatus::<vote::NetworkStatusUnverified, _, _>(
3380            &testdata_live("authority"),
3381            unwrap_unverified_for_test,
3382            Duration::ZERO,
3383        )
3384    }
3385}