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